c++11 - Remove All Elements from unordered_set -


i went through post deleting elements stl set while iterating

still, want understand why code below produces wrong result.

int main() {     unordered_set<int> adjacency;     adjacency.insert(1);     adjacency.insert(2);      (const auto& n : adjacency) {         adjacency.erase(n);     }      cout <<"after removing elements: " << endl;     (const auto& n : adjacency) {         cout << n << " ";     }     cout << endl;      return 0; } 

the adjacency contains 1 , 2. after erasing elements through for-loop, still contains element 1. why?

i using version (2) erase function below, rule "versions (1) , (3) return iterator pointing position following last of elements erased." not apply?

update: reason of not using clear() requires removing element 1 one other processing.

by position (1)  iterator erase ( const_iterator position ); key (2)   size_type erase ( const key_type& k ); range (3)    iterator erase ( const_iterator first, const_iterator last ); 

version (2) returns number of elements erased, in unordered_set containers (that have unique values), 1 if element value of k existed (and subsequently erased), , 0 otherwise.

versions (1) , (3) return iterator pointing position following last of elements erased.

thanks!

range-based for-loops use iterators under hood, wrote leads undefined behaviour.

if need process elements, , remove of them based on criteria, there way that works on containers:

for(auto = adjacency.begin(); != adjacency.end();) {     process(*it);     if (condition(*it))         = adjacency.erase(it);     else         ++it; } 

if need process items, , remove all, that:

std::for_each(adjacency.begin(), adjacency.end(), &process); adjacency.clear(); 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -