Home » C++ STL

vector::clear() function with example in C++ STL

C++ STL vector::clear() function: Here, we are going to learn about the clear() function of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 16, 2019

C++ vector::clear() function

vector::clear() is a library function of "vector" header, it is used to remove/clear all elements of the vector, it makes the 0 sized vector after removing all elements.

Note: To use vector, include <vector> header.

Syntax of vector::clear() function

    vector::clear();

Parameter(s): none – It accepts nothing.

Return value: void – It returns nothing.

Example:

    Input:
    vector<int> v1{ 10, 20, 30, 40, 50 };
    
    //clearing content of the vectors
    v1.clear();
    cout <> v1.size();

    Output:
    0

C++ program to demonstrate example of vector::clear() function

//C++ STL program to demonstrate example of
//vector::clear() function

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    //vector declaration
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //printing elements
    cout << "before clearing the elements..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //clearing all elements
    v1.clear();

    //printing elements
    cout << "after clearing the elements..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

before clearing the elements...
size of v1: 5
v1: 10 20 30 40 50
after clearing the elements...
size of v1: 0
v1:

Reference: C++ vector::clear()






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.