Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector::erase(remove(....)) is not working

Tags:

I came up with a program

#include <vector> #include <algorithm>  using namespace std;  int main() {     vector<int> a = {1,2,3,7,1,5,4};     vector<int> b = {6,7,4,3,3,1,7};     a.erase(remove(a.begin(),a.end(),a[0]),a.end());     b.erase(remove(b.begin(),b.end(),b[0]),b.end());      return 1; } 

For this specific example, my GNU gdb Ubuntu states that at return 1 line: a = {2,3,7,1,5,4} which is not expected (only deletes one 1), and b = {7,4,3,3,1} which is not expected.

My expectation is a and b should be a=2,3,7,5,4 and b=7,4,3,3,1,7.

What's going on here?

like image 866
Madhu Kumar Dadi Avatar asked Jul 02 '15 10:07

Madhu Kumar Dadi


People also ask

How do I completely delete a vector file?

clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using clear() function.

How do I remove something from a vector in C++?

The C++ vector has many member functions. Two of these member functions are erase() and pop_back(). pop_back() removes the last element from the vector. In order to remove all the elements from the vector, using pop_back(), the pop_back() function has to be repeated the number of times there are elements.

How do I erase an element from std::vector <> by 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.


2 Answers

std::remove takes the third argument by reference and it invalidates references into the range it works on (in the sense that it shifts stuff around and thus changes values of elements in the range). The problem is that you change a[0], the reference argument, during the call, which you must not do.

To fix this, pass a copy instead:

a.erase(remove(a.begin(),a.end(),int{a[0]}),a.end()); 
like image 89
Baum mit Augen Avatar answered Oct 06 '22 08:10

Baum mit Augen


Alternatively, change

a.erase(remove(a.begin(), a.end(), 1), a.end()); b.erase(remove(b.begin(), b.end(), 6), b.end()); 
like image 33
Shreevardhan Avatar answered Oct 06 '22 06:10

Shreevardhan