Reputation: 2136
I have the following code:
set<Key> test;
test.insert(key1);
test.insert(key2);
iter1 = test.find(key1);
iter2 = test.find(key2);
test.erase(iter1);
My question is, if key1 is deleted, now can I use iter2 to refer to key2 in test?
Thanks
Upvotes: 5
Views: 271
Reputation: 477150
Strictly speaking you have to check the return value of the "insert" operation and ensure that key1
and key2
don't compare equal; otherwise iter1 == iter2
and erasing iter1
invalidates iter2
. But in general see the previous answer, erasing an iterator invalidates only that iterator and no others.
Example:
struct Foo
{
Foo(std::string s = "") : s(s) { }
bool operator<(const Foo & other) { return s.size() < other.size(); }
}
std::set<Foo> x;
x.insert(Foo("Cat"));
x.insert(Foo("Dog")); // booboo
Upvotes: 3
Reputation: 2051
Asociative containers set, multiset, map and multimap are required to only invalidate iterators and references to the erased elements.
In a deque all the iterators and references are invalidated, unless the erased members are at an end (front or back) of the deque (23.2.1.3/4), in a list only the iterators and references to the erased element is invalidated (23.2.2.3/3) and on a vector every iterator and reference after the point of erase is invalidated (23.2.4.3/3)
Upvotes: 3
Reputation: 129814
Yes, set's erase
invalidates only iterators that point to the element that was erased (note that this is not necessarily true for all containers).
Upvotes: 7