Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the erase function of set in C++ change the address of other elements?

Tags:

c++

set

erase

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

like image 812
cheng Avatar asked Jun 19 '11 14:06

cheng


People also ask

What does set Erase return?

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.

Can we delete element from set?

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.

How do you remove a set element?

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.

How do you delete an element from an unordered 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.


3 Answers

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).

like image 127
Cat Plus Plus Avatar answered Sep 29 '22 20:09

Cat Plus Plus


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)

like image 21
lccarrasco Avatar answered Sep 29 '22 19:09

lccarrasco


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
like image 30
Kerrek SB Avatar answered Sep 29 '22 20:09

Kerrek SB