C++ Vector Library - clear() Function


Advertisements

Description

The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.

Declaration

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

C++98

void clear();

C++11

void clear() noexcept;

Parameters

None

Return value

None.

Exceptions

This member function never throws excpetion.

Time complexity

Linear i.e. O(n)

Example

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

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   auto ilist = {1, 2, 3, 4, 5};
   vector<int> v(ilist);

   cout << "Initial size of vector     = " << v.size() << endl;
   /* destroy vector */
   v.clear();
   cout << "Size of vector after clear = " << v.size() << endl;

   return 0;
}

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

Initial size of vector     = 5
Size of vector after clear = 0
vector.htm
Advertisements