Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't vector::clear remove elements from a vector?

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.

like image 220
Madhur Bhaiya Avatar asked Jun 24 '13 22:06

Madhur Bhaiya


People also ask

How do I completely clear a vector content?

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.

Does deleting a vector delete its contents?

Yes, the vector 's destructor will be called, and this will clear its contents.

How do you delete an element from a vector by its value?

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.

How do I remove an element from a vector string?

To remove all copies of an element from a vector , you can use std::remove like this: v. erase(std::remove(v. begin(), v.


1 Answers

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.

like image 90
Kerrek SB Avatar answered Sep 18 '22 17:09

Kerrek SB