Iterators are often used when we use STL containers in C + +. Using iterators makes it easy to perform operations such as traversal and modification of container elements.
Recently, when programming with Visual Studio 2015, it was discovered that the set iterator is directly the const_iterator type, and that the vector iterator is the normal iterator type. Come and explore with us today.
Set/map type
1 set<int>:: Iterator it1; 2 map<int,int>:: Iterator it2; 3 it1 = set1.begin (); 4 1;
above the visual Studio 2010 version, declare a collection or an iterator to a hash table, although we write ordinary iterator, but in fact they are all const_iterator, that is, a const reference that cannot be modified on the element ( the iterator set is const, and the iterator key that the map takes is const ). Therefore, if you use this iterator to modify an element in a container, it will compile without passing (such as the 3rd, 4 lines of code), and the same is true for the map iterator.
Why is the element not allowed to be modified?
I think there are two reasons for this:
① because set and map containers of this type need to be ordered according to key or to ensure the uniqueness of the element, the user is not allowed to modify the element directly. If you allow the user to modify the element directly when using iterator, the key value of the element is modified indirectly, which is likely to result in non-uniqueness or disorder.
② It is precisely because this type of container needs to maintain the order of elements, the underlying may use a data structure to save (for example: heap), if the element is frequently modified, the interior may need to be ordered multiple times, resulting in inefficiency.
How do I modify an element?
Since ordinary iterator cannot modify elements directly, what should we do? Here are two ways to do this.
① uses the container's erase () and insert () methods. If you want to modify an element, delete it directly, and then insert the modified element into the original container. The disadvantage of this method is that the efficiency is too low.
② use const_cast.
We all know that const_cast can remove any underlying const modification to make a const variable non-const, and here we use this to eliminate the const of iterator.
1 for (set<int>::iterator i = Intset.begin (); I! = Intset.end ();i++ ) 2 { 3 int &item1 = const_cast<int&> (*i); 4 // Do something here 5 }
However, I do not recommend this, although it is possible to use iterators to modify the operation of the elements, but this is contrary to the thought of the design itself.
Iterator and Const_iterator in C + + STL