C++ <vector> - size() Function
The C++ vector::size function is used to find out the total number of elements in the vector. It returns the total number of elements held in the vector, and it is not necessarily equal to its storage capacity.
Syntax
size_type size() const;
size_type size() const noexcept;
Parameters
No parameter is required.
Return Value
Number of elements present in the vector.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the vector::size function is used to find out the total number of elements in the vector called MyVector.
#include <iostream> #include <vector> using namespace std; int main (){ vector<int> MyVector{10, 20, 30, 40, 50}; cout<<"Vector size is: "<<MyVector.size()<<"\n"; cout<<"Three elements are added in the Vector.\n"; MyVector.push_back(60); MyVector.push_back(70); MyVector.push_back(80); cout<<"Now, Vector size is: "<<MyVector.size()<<"\n"; return 0; }
The output of the above code will be:
Vector size is: 5 Three elements are added in the Vector. Now, Vector size is: 8
❮ C++ <vector> Library