C ++ is not always involved, and every time it is done, it will frequently fall into the trap...
STD: Set <int> Iset;
STD: Set <int >:: iterator it = Iset. insert (4). First;
(* It) ++; // error. cause: the iterator of STD: Set cannot modify the corresponding element.
This is because:
STD: Set features:
1. For insert, delete, and search operations,
Set ensures that the time complexity is O (log N );
2. Set is an ordered container that can traverse forward and backward (bidirectional iterator );
3. Set is a container that can be configured by element types and comparison functions, but once configured, it cannot be changed;
4. The set elements can be inserted or deleted,Unchangeable.
Set is an ordered structure at any time. Once this order is damaged, set may show unexpected behavior. To ensure the conceptual integrity of the Set, C ++ STL
It specifies two limits, namely 3 and 4. In most cases, these two limits are reasonable. However, when the shared_ptr element is stored in the Set, there is no order at all. I just want to get the non-const reference of the element through the iterator. The solution is as follows: # include <iostream>
# Include <set>
Template <class T>
Inline T & getstdsetelement (STD: _ rb_tree_const_iterator <t> std_set_iterator)
{
Return * (T *) & (* std_set_iterator );
}
Int main ()
{
Using namespace STD;
set Iset;
pair : iterator, bool> res = Iset. insert (4);
int & I = getstdsetelement (res. first);
I ++;
cout <* (Iset. begin () return 0;
}