STD: The set iterator cannot modify the corresponding element.

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.