C++ Vector Library - size() Function


Advertisements

Description

The C++ function std::vector::size() returns the number of elements present in the vector.

Declaration

Following is the declaration for std::vector::size() function form std::vector header.

C++98

size_type size() const;

C++11

size_type size() const noexcept;

Parameters

None

Return value

Returns the actual objects present in vector, which may be differ than storage capacity of vector.

Exceptions

This member function never throws exception.

Time complexity

Constant i.e. O(1)

Example

The following example shows the usage of std::vector::size() function.

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v;

   cout << "Initial vector size = " << v.size() << endl;

   v.resize(128);
   cout << "Vector size after resize = " << v.size() << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Initial vector size = 0
Vector size after resize = 128
vector.htm
Advertisements