The main difference between the size() and capacity() is that the size is exaclty the number of elements in a given vector whereas the capacity is maximum number of elements a vector can have without the reallocation of the memory. When this limit is reached then the capacity is expanded automatically. The time complexity of the size() is constant.
The main distinction between size() and capacity() is that the size() returns the exact number of elements in a given vector, capacity() returns the maximum number of elements a vector may contain without reallocating memory. When this limit is achieved, the capacity is automatically increased.
SyntaxFollowing is the syntax for C++ vector::size() Function −
size_type size() const noexcept;Parameters
It doesn't accept any kind of parameter.
Example 1Let's consider the following example, where we are going to use size() function.
#include <iostream> #include <vector> using namespace std; int main(){ vector<int> tutorial{11,22,33,44}; cout << tutorial.size(); return 0; }Output
When we compile and run the above program, this will produce the following result −
4Example 2
Considering the another scenario, where we are going to take an vector with no elements and applying size() function.
#include <iostream> #include <vector> using namespace std; int main() { vector<int> myvector; cout << myvector.size(); }Output
On running the above program, it will produce the following result −
0Example 3
In the following example, we are going to use push_back() function to insert the value and then applying the size() function.
#include <iostream> #include <vector> using namespace std; int main() { vector<int> nums; nums.push_back(11); nums.push_back(22); nums.push_back(33); nums.push_back(44); cout << nums.size(); }Output
When we execute the above program, it will produce the following result −
4Example 4
Following is the another example, where we are going to take string values and applying the size() function.
#include<iostream> #include<vector> using namespace std; int main(){ vector<string> myvector{"Welcome To TP","ABCD"}; int n=myvector.size(); cout<<"Size :"<<n; return 0; }Output
On running the above program, it will produce the following result −
Size :2
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4