LogWell
LogWell

Reputation: 45

How to actually "clear" a vector in C++?

How to clear content in a simple way?

If I use vec_vec.clear(); only, there is still something in the vector that has not been cleaned up.

#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<int>> vec_vec(10);
    vec_vec[0].push_back(1);
    vec_vec[0].push_back(2);
    vec_vec[0].push_back(3);
    vec_vec[0].push_back(4);

    for (auto i : vec_vec[0])
        std::cout << i << " ";
    std::cout << "." << std::endl;

    vec_vec.clear();
    for (auto i : vec_vec[0])
        std::cout << i << " ";
    std::cout << "." << std::endl;


    vec_vec[0].clear();
    for (auto i : vec_vec[0])
        std::cout << i << " ";
    std::cout << "." << std::endl;

    for (int i=0; i<vec_vec.size(); i++)
        vec_vec.erase(vec_vec.begin() + i);
    for (auto i : vec_vec[0])
        std::cout << i << " ";
    std::cout << "." << std::endl;
    
    return 0;
}
1 2 3 4 *
0 0 3 4 *
*
*

Upvotes: 1

Views: 157

Answers (1)

aschepler
aschepler

Reputation: 72473

vec_vec.clear();
for (auto i : vec_vec[0])

After this clear, vec_vec is empty, so the expression vec_vec[0] has undefined behavior.

Undefined behavior means anything at all might happen, and it's the fault of the program, not the fault of the C++ compiler, library, etc. So it might act like an empty vector, it might crash your program, it might print some values, or it might do what you expect today, then break at the worst possible time later on.

See also this Q&A on Undefined, unspecified, and implementation-defined behavior.

Upvotes: 3

Related Questions