Home > php教程 > PHP开发 > Use of Iterator in c++ STL standard container

Use of Iterator in c++ STL standard container

高洛峰
Release: 2016-12-13 17:33:52
Original
1258 people have browsed it

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();  
}
Copy after login

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;
Copy after login

Cpp code

}
Copy after login

Cpp code

map<int,int>::reverse_iterator rit;  
for(rit = amap.rbegin();rit != amap.rend();rit++)//从后向前  
{  
     cout<<"key:"<<rit->first<<" value:"<<rit->second<<endl;  
}
Copy after login

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.


Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template