C++

C++ Vector Clear vs Erase

The C++ vector has many member functions. Two of them are clear() and erase(). clear() “removes” all the elements of the vector. erase() “removes” a single element or a range of elements. There are two overloaded variants of the erase() member function for the vector.

The title of this article is actually “Vector clear() Member Function versus Vector erase() Member Function, in C++”. This is a comparison of the two-member functions. It deals with when to use which, how to use which, and under which conditions either is used.

In order to use a vector in a C++ program, the program should begin with:

#include <vector>

#include <iostream>

using namespace std;

Article Content

Vector clear()

The clear() member function “removes” all the elements of the vector. Its syntax is:

void clear()

It returns void. The following program illustrates its use, with the expression, “vtr.clear();”:

#include <vector>

#include <iostream>

using namespace std;

 

int main()

{

    vector<char> vtr = {'P', 'Q', 'R', 'S', 'T', 'U'};

 

    for (vector<char>::iterator it = vtr.begin(); it != vtr.end(); it++)

        cout << *it << ' ';

    cout << endl;

 

    vtr.clear();

 

    for (vector<char>::iterator it = vtr.begin(); it != vtr.end(); it++)

        cout << *it << ' ';

    cout << endl;

 

    return 0;

}

The output is the one line:

P Q R S T U

If the vector had not been cleared, the output would have been two lines of the same sequence. No second line was displayed because all the elements were cleared.

const vector and clear()

When a vector declaration is preceded by const, it means the elements of the vector cannot be deleted or changed. If an expression attempts to change or delete any of the elements, the program will not compile. Test the following program and note that it does not compile:

#include <vector>

#include <iostream>

using namespace std;

 

int main()

{

    const vector<char> vtr = {'P', 'Q', 'R', 'S', 'T', 'U'};

 

    for (vector<char>::const_iterator it = vtr.begin(); it != vtr.end(); it++)

        cout << *it << ' ';

    cout << endl;

 

    vtr.clear();

 

    for (vector<char>::const_iterator it = vtr.begin(); it != vtr.end(); it++)

        cout << *it << ' ';

    cout << endl;

 

    return 0;

}

If the program were tested, an error message would have been issued, and there would not have been any compilation. Because the vector was declared constant, the clear() function could not operate, resulting in an error message from the compiler.

Note: clear() deletes all the elements of the vector. Actually, it earmarks all the elements as deleted, such that other codes can take up their memory locations. If the memory location of any element has not yet been taken up by another code, then the element can still be reused on behalf of the same vector.

Vector Erase

The simplified syntaxes for the two erase() member functions are:

    a.erase(q)

and

    a.erase(q1,q2)

where a is the name of the vector.

iterator erase(const_iterator position)

This is the full syntax for “a.erase(q)”. It returns an iterator pointing to the element, which was just behind the one erased. The argument, q is an iterator pointing to the element to be erased. The following program illustrates this:

#include <vector>

#include <iostream>

using namespace std;

 

int main()

{

    vector<char> vtr = {'P', 'Q', 'R', 'S', 'T', 'U'};

 

    vector<char>::iterator iter = vtr.begin();

    ++iter; ++iter;

 

    vector<char>::iterator it = vtr.erase(iter);

 

    for (int i=0; i < vtr.size(); i++) {

        cout << vtr[i] << ' ';

    }

    cout << endl;

 

    cout << *it << endl;

 

    return 0;

}

The output is:

P Q S T U

S

‘R’ has been deleted. The returned iterator now points to ‘S’, which was just after ‘R’. The member function, begin(), returns an iterator that points to the first element of the vector. In the code, this iterator was incremented two times to point to ‘R’. ‘R’ was erased with the expression, “vtr.erase(iter)”.

Range in Vector

For the list,

'P', 'Q', 'R', 'S', 'T', 'U'

the sequence, ‘Q’, ‘R’, ‘S’, ‘T’ is a range. However, with C++ containers, the last element, ‘T’ is not considered part of the range. This is indicated in general terms as:

[i, j)

or

[q1, q2)

‘[’ in this case, means that the first element in the sequence is included, and ‘)’ means the last element is not included.

iterator erase(const_iterator first, const_iterator last)

This is the full syntax for “a.erase(q1,q2)”. It returns an iterator pointing to the element, which was just behind the range erased. Note: the last element in the range is not erased. So, the returned iterator will point to the last element of the range. The arguments q1and q2 are iterators pointing to the first and last elements of the range. The following program illustrates this:

#include <vector>

#include <iostream>

using namespace std;

 

int main()

{

    vector<char> vtr = {'P', 'Q', 'R', 'S', 'T', 'U'};

 

    vector<char>::iterator itB = vtr.begin();

    ++itB;

    vector<char>::iterator itE = vtr.end();

    --itE; --itE;

 

    vector<char>::iterator it = vtr.erase(itB, itE);

 

    for (int i=0; i < vtr.size(); i++) {

        cout << vtr[i] << ' ';

    }

    cout << endl;

 

    cout << *it << endl;

 

    return 0;

}

The output is:

P T U

T

‘Q’, ‘R’, ‘S’ have been deleted. The returned iterator now points to ‘T’, which was the last element in the container range. The member function, end(), returns an iterator that points just after the last element of the vector. In the code, this iterator was decremented two times to point to ‘T’, the last element of the range. ‘Q’, ‘R’, ‘S’ were deleted without the last element, ‘T’ in the range, with the expression, “vtr.erase(itB, itE)”.

const vector and erase()

If the declaration of a vector is preceded with const, for constant, then none of its elements can be erased. The following program will not compile, issuing an error message for the a.erase(q) expression:

#include <vector>

#include <iostream>

using namespace std;

 

int main()

{

    const vector<char> vtr = {'P', 'Q', 'R', 'S', 'T', 'U'};

 

    vector<char>::const_iterator iter = vtr.begin();

    ++iter; ++iter;

 

    vector<char>::const_iterator it = vtr.erase(iter);

 

    for (int i=0; i < vtr.size(); i++) {

        cout << vtr[i] << ' ';

    }

    cout << endl;

 

    cout << *it << endl;

 

    return 0;

}

If the reader tried the program, he would have received an error message. The program would not have compiled.

The following program will not compile, issuing an error message for the a.erase(q1,q2) expression:

#include <vector>

#include <iostream>

using namespace std;

 

int main()

{

    const vector<char> vtr = {'P', 'Q', 'R', 'S', 'T', 'U'};

 

    vector<char>::const_iterator itB = vtr.begin();

    ++itB;

    vector<char>::const_iterator itE = vtr.end();

    --itE; --itE;

 

    vector<char>::const_iterator it = vtr.erase(itB, itE);

 

    for (int i=0; i < vtr.size(); i++) {

        cout << vtr[i] << ' ';

    }

    cout << endl;

 

    cout << *it << endl;

 

    return 0;

}

Note: erase() deletes an element or a range of elements. Actually, it earmarks an element as deleted, such that their memory locations can be taken up by other codes. If the memory location of any element has not yet been taken up by another code, then the element can still be reused on behalf of the same vector.

pop_back()

The pop_back() vector member function is a kind of erase() function. However, it deletes only the last element of the vector. The syntax is:

void pop_back()

It takes no argument and returns void. The following program illustrates its use:

#include <vector>

#include <iostream>

using namespace std;

 

int main()

{

    vector<char> vtr = {'P', 'Q', 'R', 'S', 'T', 'U'};

 

    vtr.pop_back();

 

    for (int i=0; i < vtr.size(); i++) {

        cout << vtr[i] << ' ';

    }

    cout << endl;

 

    return 0;

}

The output is:

P Q R S T

The last element, ‘U’ has been removed (erased).

Destroying a Vector

Can a vector be destroyed? – Yes! However, when a vector is destroyed, all its elements are erased except its name; meaning the vector declaration can still be reused, but with some uncertainty. The syntax to destroy a vector is:

a.~X()

where ‘a’ is the name of the vector. The following program illustrates this:

#include <vector>

#include <iostream>

using namespace std;

 

int main()

{

        vector<char> vtr = {'P', 'Q', 'R', 'S', 'T', 'U'};

 

        vtr.~vector();

 

        vtr = {'V', 'W', 'X', 'Y', 'Z'};

 

        for (int i=0; i < vtr.size(); i++) {

            cout << vtr[i] << ' ';

        }

        cout << endl;

 

        vtr.~vector();

 

        vtr.push_back('A');

        vtr.push_back('B');

        vtr.push_back('C');

        vtr.push_back('D');

        vtr.push_back('E');

 

        for (int i=0; i < vtr.size(); i++) {

            cout << vtr[i] << ' ';

        }

        cout << endl;

        return 0;

}

The output is:

    V W X Y Z
    p ^ t e @ A  C D E

from the author’s computer, with some unreliable characters for the second line.

Conclusion

The vector member function clear() can be compared to the vector member function erase(). They are not substitutes. clear() deletes all the elements of the vector. Actually, it earmarks all the elements as deleted, such that their memory locations can be taken up by other codes. If the memory location of any element has not yet been taken up by another code, then the element can still be reused on behalf of the same vector. erase() deletes an element or a range of elements. Actually, it earmarks an element as deleted, such that the memory location can be taken up by another code. If the memory location of any element deleted has not yet been taken up by another code, then the element can still be reused on behalf of the same vector. clear has similarity to destroy, ~X().

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.