Home  >  Article  >  php教程  >  Use of Iterator in c++ STL standard container

Use of Iterator in c++ STL standard container

高洛峰
高洛峰Original
2016-12-13 17:33:521225browse

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.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Usage of s:iteratorNext article:Usage of s:iterator