1

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 *
*
*
cigien
  • 57,834
  • 11
  • 73
  • 112
LogWell
  • 45
  • 7
  • Have you tried std::vector's erase function? – Dylan Fouche Sep 19 '20 at 15:04
  • 3
    Attempting to access a vector out of bounds causes undefined behavior. You do that after `.clear()`ing it. – HolyBlackCat Sep 19 '20 at 15:05
  • 2
    @DylanFouche There's nothing wrong with `clear`. It does what the OP wants. – cigien Sep 19 '20 at 15:12
  • Your code invokes [undefined behaviour](https://en.cppreference.com/w/cpp/language/ub) and is thus simply broken and *any* result is ok. Once you break the language rules and do something you are not allowed to do, you leave the realm of well defined behaviour. The compiler is not required to prevent you from breaking the rules, it can just generate garbage if you do. It is entirely on *you* to know *all* the rules and follow them at all times - which you didn't here. – Jesper Juhl Sep 19 '20 at 15:13
  • That code didn’t produce the output listed in the question. The code doesn’t write any *s. – Pete Becker Sep 19 '20 at 18:12

1 Answers1

3
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.

aschepler
  • 70,891
  • 9
  • 107
  • 161