vector::clear() function in C++

In C++, the vector class provides a function clear(). It removes all elements from the calling vector object. It will make the size of vector 0.

Table Of Contents

Syntax of vector::clear():

void clear();

Parameters:

None

Return value:

Advertisements

None

Examples of vector::clear()

Let’s see some examples of clear() function of vector class.

Example 1

Suppose we have a vector of int. It contains five elements. We will prints its size, and it should print 5. Then we will call the vector::clear() to delete all elements from the vector. After that, we will again print the vector size. This time size should be zero. Let’s see an example,

#include <iostream>
#include <vector>

int main ()
{
    // create a vector, and initialize with seven integers
    std::vector<int> vectorObj {11, 12, 13, 14, 15, 16, 17};

    std::cout<< "Size of vector is: "<< vectorObj.size() << std::endl;

    // Remove all elements from vector
    vectorObj.clear();

    std::cout<< "Size of vector is: "<< vectorObj.size() << std::endl;

    return 0;
}

Output:

Size of vector is: 7
Size of vector is: 0

It deleted all the elements from the vector, and made its size 0.

Example 2

Suppose we have a vector of strings. It contains five elements. We will prints its size, and it should print 5. Then we will call the vector::clear() to delete all strings from the vector. After that, we will again print the vector size. This time size should be zero. Let’s see an example,

#include <iostream>
#include <vector>
#include <string>

int main ()
{
    // create a vector, and initialize with five strings
    std::vector<std::string> vectorObj {"Hi", "this", "is", "a", "sample"};

    std::cout<< "Size of vector is: "<< vectorObj.size() << std::endl;

    // Remove all elements from vector
    vectorObj.clear();

    std::cout<< "Size of vector is: "<< vectorObj.size() << std::endl;

    return 0;
}

Output:

Size of vector is: 7
Size of vector is: 0

It deleted all the elements from the vector, and made its size 0.

Summary

We learned how to use the clear() function of vector in C++. Thanks.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top