Detailed explanation of STL iterator usage

Detailed explanation of C++ STL iterator usage

Whether it is a sequence container or an association container, the most common operation is undoubtedly to traverse the elements stored in the container. In most cases, the "iterator" will be used to realize this operation. So what exactly is an iterator?

We know that although different containers have different internal structures, they are essentially used to store a large amount of data. In other words, they are a series of storage units that can store multiple data. Therefore, the operation methods that need to traverse the data, such as sorting, searching and summation of data, should be similar.

Since they are similar, we can use generic technology to design them into a general algorithm suitable for all containers, so as to separate containers from algorithms. However, to achieve this goal, a device similar to an intermediary is required. In addition to the ability to traverse the container and read and write data, it should also be able to hide the internal differences of the container, so as to transmit data to the algorithm with a unified interface.

This is the inevitable result of the development of generic thinking, so the iterator came into being. Simply put, iterators and C++ of Pointer Very similar, it can be any type you need. You can point to an element in the container through the iterator, and read / write the element if necessary.

Iterator class

The commonly used iterators are divided into input iterators, output iterators, forward iterators, bidirectional iterators and random access iterators according to their functional strength.

  1. forward iterator
    Assuming that p is a forward iterator, p supports + + p, p + +, * p operations, and can also be copied or assigned. You can use = = and= Operator. In addition, two forward iterators can assign values to each other.

  2. bidirectional iterator
    Bidirectional iterators have all the functions of forward iterators. In addition, assuming that p is a bidirectional iterator, you can also perform -- p or p -- operations (that is, move backward one position at a time).

  3. random access iterator
    Random access iterators have all the functions of bidirectional iterators. In addition, assuming that p is a random access iterator and i is an integer variable or constant, p also supports the following operations:

  • p+=i: make p move back i elements.
  • p-=i: move p forward by i elements.
  • p+i: returns the iterator of the ith element after p.
  • p-i: returns the iterator of the ith element before p.
  • p[i]: returns the reference of the ith element after p.

In addition, the two random access iterators P1 and P2 can also be compared with <, >, < =, > = operators. In addition, the expression p2-p1 is also defined, and its return value represents the difference between the sequence number of the element pointed to by P2 and the element pointed to by P1 (it can also be said that the number of elements between P2 and P1 minus one).

Iterator types specified by different containers in the C++ 11 standard:

containerCorresponding iterator type
arrayrandom access iterators
vectorrandom access iterators
dequerandom access iterators
listBidirectional Iterator
set / multisetBidirectional Iterator
map / multimapBidirectional Iterator
forward_listforward iterators
unordered_map / unordered_multimapforward iterators
unordered_set / unordered_multisetforward iterators
stackIterators are not supported
queueIterators are not supported

How iterators are defined

Iterator definition modeSpecific format
Forward iteratorContainer class name:: iterator iterator name;
Constant forward iteratorContainer class name:: const_iterator iterator name;
reverse iterator Container class name:: reverse_iterator iterator name;
Constant inverse iteratorContainer class name:: const_reverse_iterator iterator name;

Example 1

/*******************************************************************
 *   > File Name: vector-iterator.cpp
 *   > Create Time: 2021 15:11:00, September 27
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    /* Create a vector container v */
    vector<int> v{1, 2, 3, 4, 4, 6, 7, 8, 9, 10};
    cout << "1--------------" << endl;

    for(int i = 0; i< (int)v.size(); i++){
        cout << v[i] << " ";
    }

    cout << endl << "2--------------" << endl;
    vector<int>::iterator i; // Create a forward iterator
    for(i = v.begin(); i != v.end(); i++){
        cout << *i << " ";
    }

    cout << endl << "3--------------" << endl;
    for(i = v.begin(); i < v.end(); i++){
        cout << *i << " ";
    }

    cout << endl << "4--------------" << endl;
    i = v.begin();
    while(i != v.end()){
        cout << *i << " ";
        i += 2;
    }

    return 0;
}

Compile and run:

PS E:\fly-prj\cplusplus\day20> .\vector-iterator.exe
1--------------
1 2 3 4 4 6 7 8 9 10
2--------------
1 2 3 4 4 6 7 8 9 10
3--------------
1 2 3 4 4 6 7 8 9 10
4--------------
1 3 4 7 9

Example 2

Arrays are also containers. The iterator of an array is a pointer and a random access iterator.

/*******************************************************************
 *   > File Name: array-test.cpp
 *   > Create Time: 2021 September 27, 2006 16:13:19
 ******************************************************************/
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    int a[10] = {1,2,3,4,5,6,7,8,9,10};

    int* p = a; // p is the iterator of a
    for(int i = 0; i < 10; i++){
        printf("%d ", *p);
        p++;
    }

    return 0;
}

Compile and run:

PS E:\fly-prj\cplusplus\day20> make 
g++ -o array-test array-test.cpp -g -Wall
PS E:\fly-prj\cplusplus\day20> .\array-test.exe
1 2 3 4 5 6 7 8 9 10

Example 3

/*******************************************************************
 *   > File Name: list-const_iterator.cpp
 *   > Create Time: 2021 September 27, 2016 16:46:41
 ******************************************************************/
#include <iostream>
#include <vector>
#include <list>
using namespace std;

int main(int argc, char* argv[])
{
    list<int> v;
    list<int>::const_iterator  i; /*Create a constant forward iterator*/

    /* OK */
    for(i = v.begin(); i!= v.end(); ++i){
        cout << *i ;
    }

    #if 0 / * does not support the < operator*/
    // ERR:no match for 'operator<' (operand types are 'std::list<int>::const_iterator' and 'std::list<int>::iterator')
    for(i = v.begin(); i < v.end(); ++i){
        cout << *i;
    }
    #endif

    #if 0 / * subscript access is not supported*/
    // ERR:no match for 'operator[]' (operand types are 'std::list<int>' and 'int')
    for(int i = 0; i < v.size(); ++i){
        cout << v[i];
    }
    #endif

    return 0;
}

C++ STL standard manual

Tags: Python C++

Posted on Mon, 27 Sep 2021 04:39:53 -0400 by robche