×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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

Syntax of vector::clear() function

vector::clear();

Parameter(s)

none – It accepts nothing.

Return value

void – It returns nothing.

Sample Input and Output

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()

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.