STL之Iterator(迭代器)

概述

根据迭代器功能的不同,将迭代器分为以下几类:

Iterator CategoryAbilityProviders
Input iteratorReads forwardistream
Output iteratorWrites forwardostream, inserter
Forward iteratorReads and writes forward 
Bidirectional iterator(双向迭代器)Reads and writes forward and backwardlist, set, multiset, map, multimap
Random access iteratorReads and writes with random accessvector, deque string, array

下面,逐一分析各种迭代器。

输入迭代器

  Input iterators can only step forward element-by-element with read access. Thus, they return values elementwise

  输入迭代器的操作:

Table 7.2. Operations of Input Iterators

ExpressionEffect
*iterProvides read access to the actual element
iter ->memberProvides read access to a member (if any) of the actual element
++iterSteps forward (returns new position)
iter++Steps forward (returns old position)
Iter1 == iter2Returns whether two iterators are equal
Iter1 != iter2Returns whether two iterators are not equal
TYPE(iter)Copies iterator (copy constructor)

  注意:输入迭代器只能够读取一次元素。几乎所有其他迭代器都有输入迭代器的功能。

输出迭代器

  Output iterators are the counterparts of input iterators. They can only step forward with write access. Thus, you can assign new values only element-by-element. You can't use an output iterator to iterate twice over the same range. The goal is to write a value into a "black hole" (whatever that means). So, if you write something for the second time at the same position into the same black hole, it is not guaranteed that you will overwrite a previous value. Table 7.3 lists the valid operations for output iterators. The only valid use of operator * is on the left side of an assignment statement.

Table 7.3. Operations of Output Iterators

ExpressionEffect
*iter = valueWrites value to where the iterator refers
++iterSteps forward (returns new position)
iter++Steps forward (returns old position)
TYPE (iter)Copies iterator (copy constructor)
前向迭代器

  前向迭代器是输入迭代器和输出迭代器的组合。它包含输入迭代器的所有功能和输出迭代器的大部分功能。

  下面是前向迭代器的操作:

Table 7.4. Operations of Forward Iterators

ExpressionEffect
*iterProvides access to the actual element
iter-> memberProvides access to a member of the actual element
++iterSteps forward (returns new position)
iter++Steps forward (returns old position)
iter1 == iter2Returns whether two iterators are equal
iter1 != iter2Returns whether two iterators are not equal
TYPE()Creates iterator (default constructor)
TYPE(iter)Copies iterator (copy constructor)
iter1 = iter2

Assigns an iterator

  Unlike input iterators and output iterators, forward iterators can refer to the same element in the same collection and process the same element more than once.

为什么前向迭代器只包含输出迭代器的大部分功能,而不是全部功能呢?

  对于输出迭代器,在不检查是不是队列的末尾就写数据是正确的。事实上,是不可以将一个输出迭代器和一个终端迭代器作比较的,因为输出迭代器没有对比的操作。

复制代码

//OK for output iterators
   //ERROR for forward iterators
   while (true) {
       *pos = foo();
        ++pos;
   }

复制代码

  对于前向迭代器,在访问迭代器指向的数据之前,必须确定该迭代器是否是正确的。这就是为什么上面的循环中的代码对前向迭代器是错误的。如果该迭代器指向的是NULL,那么在没有检查之前便去访问未知地址,会出现未定义行为。

复制代码

//OK for forward iterators
   //IMPOSSIBLE for output iterators
   while (pos != coll.end()) {
       *pos = foo();
       ++pos;
   }

复制代码

双向迭代器

  Bidirectional iterators are forward iterators that provide the additional ability to iterate backward over the elements. Thus, they provide the decrement operator to step backward (Table 7.5).

Table 7.5. Additional Operations of Bidirectional Iterators

ExpressionEffect
-- iterSteps backward (returns new position)
iter--Steps backward (returns old position)

随机访问迭代器

Random access iterators are bidirectional iterators that can perform random access. Thus, they provide operators for "iterator arithmetic" (in accordance with the "pointer arithmetic" of ordinary pointers). That is, they can add and subtract offsets, process differences, and compare iterators with relational operators such as < and >. Table 7.6 lists the additional operations of random access iterators.

Random access iterators are provided by the following objects and types:

  • Containers with random access (vector, deque)

  • Strings (string, wstring)

  • Ordinary arrays (pointers)

Table 7.6. Additional Operations of Random Access Iterators

ExpressionEffect
iter[n]Provides access to the element that has index n
iter+=nSteps n elements forward (or backward, if n is negative)
iter-=nSteps n elements backward (or forward, if n is negative)
iter+nReturns the iterator of the nth next element
n+iterReturns the iterator of the nth next element
iter-nReturns the iterator of the nth previous element
iter1-iter2Returns the distance between iter1 and iter2
iter1<iter2Returns whether iter1 is before iter2
iter1>iter2Returns whether iter1 is after iter2
iter1<=iter2Returns whether iter1 is not after iter2
iter1>=iter2Returns whether iter1 is not before iter2

显示详细信息

The following program demonstrates the special abilities of random access iterators:

复制代码

// iter/itercat.cpp

   #include <vector>
   #include <iostream>
   using namespace std;


   int main()
   {
      vector<int> coll;


      //insert elements from -3 to 9
      for (int i=-3; i<=9; ++i) {
          coll.push_back (i);
      }


      /* print number of elements by processing the distance between beginning and end
       * - NOTE: uses operator -for iterators
       */
      cout << "number/distance: " << coll.end()-coll.begin() << endl;


      /* print all elements
       * - NOTE: uses operator < instead of operator ! =
       */
      vector<int>::iterator pos;
       for (pos=coll.begin(); pos<coll.end(); ++pos) {
           cout << *pos << ' '; 
       }
       cout << endl;


       /* print all elements
        * - NOTE: uses operator [ ] instead of operator *
        */
       for (int i=0; i<coll.size(); ++i) {
           cout << coll.begin() [i] << ' ';
       }
       cout << endl;


       /* print every second element
        * - NOTE: uses operator +=
        */
       for (pos = coll.begin(); pos < coll.end()-1; pos += 2) {
           cout << *pos << ' ';
       }
       cout << endl;
   }

复制代码

The output of the program is as follows:

					
   number/distance: 13
   -3 -2 -1 0 1 2 3 4 5 6 7 8 9
   -3 -2 -1 0 1 2 3 4 5 6 7 8 9
   -3 -1 1 3 5 7

STL之Iterator(迭代器) - wiessharling - 博客园 (cnblogs.com)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值