📄 capacity.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head> <meta name="generator" content= "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org"> <title>capacity</title> <link href="../cppreference.css" rel="stylesheet" type="text/css"></head><body><table> <tr> <td> <div class="body-content"> <div class="header-box"> <a href="../index.html">cppreference.com</a> > <a href= "index.html">C++ Vectors</a> > <a href= "capacity.html">capacity</a> </div> <div class="name-format"> capacity </div> <div class="syntax-name-format"> Syntax: </div> <pre class="syntax-box"> #include <vector> <strong>size_type</strong> capacity() const;</pre> <p>The capacity() function returns the number of elements that the vector can hold before it will need to allocate more space.</p> <p>For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size, the other method calls the reserve function to achieve a similar goal:</p> <pre class="example-code"> vector<int> v1(10); cout << "The capacity of v1 is " << v1.capacity() << endl; vector<int> v2; v2.reserve(20); cout << "The capacity of v2 is " << v2.capacity() << endl; </pre> <p>When run, the above code produces the following output:</p> <pre class="example-code"> The capacity of v1 is 10 The capacity of v2 is 20 </pre> <p>C++ containers are designed to grow in size dynamically. This frees the programmer from having to worry about storing an arbitrary number of elements in a container. However, sometimes the programmer can improve the performance of her program by giving hints to the compiler about the size of the containers that the program will use. These hints come in the form of the <a href= "reserve.html">reserve</a>() function and the constructor used in the above example, which tell the compiler how large the container is expected to get.</p> <p>The capacity() function runs in <a href= "../complexity.html">constant time</a>.</p> <div class="related-name-format"> Related topics: </div> <div class="related-content"> <a href="reserve.html">reserve</a><br> <a href="resize.html">resize</a><br> <a href="size.html">size</a> </div> </div> </td> </tr> </table></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -