0

I didnt understand how clear() works in the vector. when I perform vector.clear(); it still displays the elements of the vector but size becomes 0

code :

vector<int> a(5,10);
    cout << "\nSize of vector a : " << a.size() << endl;
    cout << "vector a : ";
    for (int i=0; i<5; i++) {
        cout << a[i] << " ";
    }

    a.clear();
    cout << "\nSize of vector a after clear : " << a.size() << endl;

    int is_empty = a.empty();
    if (is_empty == 1) {
        cout << "vector is empty." << endl;
    }

    cout << "vector a : ";
    for (int i=0; i<5; i++) {
        cout << a[i] << " ";
    }

Output :

Size of vector a : 5
vector a : 10 10 10 10 10
Size of vector a after clear : 0
vector is empty.
vector a : 10 10 10 10 10 
  • 1
    You are looking at elements that are not yours to look at. https://en.cppreference.com/w/cpp/language/ub – Captain Giraffe Aug 06 '23 at 07:47
  • 1
    `for (int i=0; i<5; i++) { cout << a.at(i) << " "; }` -- Try that and report back your results. – PaulMcKenzie Aug 06 '23 at 07:49
  • 1
    If you use an index that is equal to or larger than the vectors size (or negative), then you are out of bounds and will have *undefined behavior*. – Some programmer dude Aug 06 '23 at 07:50
  • 3
    *when I perform vector.clear(); it still displays the elements of the vector but size becomes 0* -- What did you expect to happen by accessing items out-of-bounds? If you expected a crash, or a big error box saying "you made a mistake", C++ doesn't work this way. Using `[]` to access out-of-bounds elements is undefined behavior. – PaulMcKenzie Aug 06 '23 at 07:53
  • 1
    Look at the documentation for [std::vector::clear](https://en.cppreference.com/w/cpp/container/vector/clear) -> *Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterators are also invalidated*. In other words you should not use the content of the vector anymore. For performance reasons vector's memory is still there (and that's why you don't get crashes). But a program that runs and seemingly gives the correct answers is NOT necessarily a correct one. – Pepijn Kramer Aug 06 '23 at 07:56
  • 1
    You are accessing a vector out of bounds. When you do that the results are unpredictable. You might get an error, you might get garbage values, you might get the values that were there previously, or you might get something else completely. The technical term for this is *undefined behaviour* and that's what your program has. – john Aug 06 '23 at 08:15

0 Answers0