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
setname. erase(startingposition, endingposition) Parameters : Position of the element to be removed in the form of iterator or the range specified using start and end iterator. Result : Elements are removed from the specified position of the container.
The remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.
Deleting a single element from the set container is very simple in C++. The idea is to pass the given element to the set::erase function, which erases it from the set.
The unordered_set::erase() function is a built-in function in C++ STL which is used to remove either a single element or a group of elements ranging from start(inclusive) to end(exclusive). This decreases the size of a container by the number of elements removed.
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).
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With