Halym2007's blog

By Halym2007, history, 3 years ago, In English

both code did same.what is the difference?

First one : 
set <int> s;
s.insert (1);s.insert (3);s.insert (5);
auto tr = s.lower_bound (2);
s.erase (tr);<-----------here
--------------------------
Second one : 
set <int> s;
s.insert (1);s.insert (3);s.insert (5);
auto tr = s.lower_bound (2);
s.erase (*tr);<-----------here
  • Vote: I like it
  • +40
  • Vote: I do not like it

| Write comment?
»
3 years ago, hide # |
 
Vote: I like it +3 Vote: I do not like it

Auto comment: topic has been updated by Halym2007 (previous revision, new revision, compare).

»
3 years ago, hide # |
 
Vote: I like it +3 Vote: I do not like it

Auto comment: topic has been updated by Halym2007 (previous revision, new revision, compare).

»
3 years ago, hide # |
← Rev. 4  
Vote: I like it -22 Vote: I do not like it

.

»
3 years ago, hide # |
← Rev. 3  
Vote: I like it +68 Vote: I do not like it

The real difference is when you use multiset and have multiple values, the first code removes only one occurrence of 3(lower_bound of 2 in the set is 3) but the second one removes all of them.

The reason is that tr is a pointer to one element, while *tr is the value of the pointer, which when used in a multiset, removes all occurrences of that element.

»
3 years ago, hide # |
 
Vote: I like it +1 Vote: I do not like it

tr is an iterator so is pointing to the memory address while *tr means dereferencing the iterator and is accessing value at that memory address

»
3 years ago, hide # |
 
Vote: I like it +16 Vote: I do not like it

First One s.erase(tr) -> O(1)

Second One s.erase(*tr) -> O(logN)