When I use clear()
on a std::vector
, it is supposed to destroy all the elements in the vector
, but instead it doesn't.
Sample code:
vector<double> temp1(4); cout << temp1.size() << std::endl; temp1.clear(); cout << temp1.size() << std::endl; temp1[2] = 343.5; // I should get segmentation fault here .... cout << "Printing..... " << temp1[2] << endl; cout << temp1.size() << std::endl;
Now, I should have gotten segmentation fault while trying to access the cleared vector, but instead it fills in the value there (which according to me is very buggy)
Result looks as follows:
4 0 Printing..... 343.5 0
Is this normal? This is a very hard bug to spot, which basically killed my code for months.
All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.
Yes, the vector 's destructor will be called, and this will clear its contents.
You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector. erase(std::remove(myVector. begin(), myVector.
To remove all copies of an element from a vector , you can use std::remove like this: v. erase(std::remove(v. begin(), v.
You have no right to get a segmentation fault. For that matter, a segmentation fault isn't even part of C++. Your program is removing all elements from the vector, and you're illegally accessing the container out of bounds. This is undefined behaviour, which means anything can happen. And indeed, something happened.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With