Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing item from vector while iterating?

Tags:

c++

iterator

stl

I have a vector that holds items that are either active or inactive. I want the size of this vector to stay small for performance issues, so I want items that have been marked inactive to be erased from the vector. I tried doing this while iterating but I am getting the error "vector iterators incompatible".

vector<Orb>::iterator i = orbsList.begin();      while(i != orbsList.end()) {         bool isActive = (*i).active;          if(!isActive) {             orbsList.erase(i++);         }         else {             // do something with *i             ++i;         }     } 
like image 423
Lucas Avatar asked Jan 17 '11 12:01

Lucas


People also ask

How do you delete an element from a vector while iterating?

To delete single element from a vector using erase() function, pass the iterator of element to it like erase(it). It will delete the element pointed by the iterator the it variable. To delete multiple elements from a vector using erase() function, pass the iterator range to it like erase(start, end-1).

How do I remove a specific value from a vector?

The erase() function can remove an element from the beginning, within, or end of the vector. In order to remove all the elements from the vector, using erase(), the erase() function has to be repeated the number of times there are elements, beginning from the first element.

How do you remove from set while iterating?

Using an iterator We can use the remove() method provided by the Iterator interface that removes the latest element returned by the iterator. Please note we should not modify the set after the iterator is created (except through the iterator's own remove method); otherwise, a ConcurrentModificationException is thrown.

How do I remove an item from a vector in C++?

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.


1 Answers

The most readable way I've done this in the past is to use std::vector::erase combined with std::remove_if. In the example below, I use this combination to remove any number less than 10 from a vector.

(For non-c++0x, you can just replace the lambda below with your own predicate:)

// a list of ints int myInts[] = {1, 7, 8, 4, 5, 10, 15, 22, 50. 29}; std::vector v(myInts, myInts + sizeof(myInts) / sizeof(int));  // get rid of anything < 10 v.erase(std::remove_if(v.begin(), v.end(),                         [](int i) { return i < 10; }), v.end()); 
like image 146
Moo-Juice Avatar answered Sep 21 '22 13:09

Moo-Juice