Most standard containers of C++ STL provide Iterator. Some containers, such as priority_queue, do not have Iterator because semantically they should not allow arbitrary traversal of elements in the container.
There is the iterator pattern among the 23 classic design patterns, and the java collection framework also implements this pattern:
Java code
package java.util; public interface Iterator<E> { boolean hasNext(); E next(); void remove(); }
C++’s iterator is more flexible than java, mainly reflected in:
1.java only A front-to-back iterator. In addition to front-to-back iterators, c++ also provides back-to-back iterators, such as:
Cpp code
map<int,int> amap; amap.insert(pair<int,int>(1,1)); amap.insert(pair<int.int>(2,2)); map<int,int>::iterator it; for(it = amap.begin();it != ampa.end();it++)//从前向后 { cout<<"key:"<<it->first<<" value:"<<it->second<<endl;
Cpp code
}
Cpp code
map<int,int>::reverse_iterator rit; for(rit = amap.rbegin();rit != amap.rend();rit++)//从后向前 { cout<<"key:"<<rit->first<<" value:"<<rit->second<<endl; }
2. In addition to iterator, c++ also provides const_iterator, which can only read the data in the collection, but cannot change its value.
3. Java’s iterator seems to only be able to increment in a single step, while c++’s iterator In addition, the iterator can also implement arithmetic operations, such as +n, -n, which is very useful for scenarios where a certain element needs to be read randomly. However, it seems that only the iterator of vector supports arithmetic operations. In other words, the iterator it in the previous example cannot perform operations such as it = it+n. This is important to remember.