再探迭代器


除了爲每一個容器定義的迭代器以外,標準庫在頭文件iterator中還定義了額外幾種迭代器,包括:ios


插入迭代器(insert iterator):這些迭代器被綁定到一個容器上,可用來向容器中插入元素;post

插入器有三種類型this

  1. back_inserterspa

  2. front_insertercode

  3. insert
    ci

流迭代器(stream iterator): 這些迭代器被綁定到輸入或輸出流上,可用來便利全部關聯的IO流;element

istream_iteratorrem

ostream_itratorget


#include <list>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;

void main()
{
	vector<int> vec;
	istream_iterator<int> in_iter(cin);  // read ints from cin
	istream_iterator<int> eof;           // istream ``end'' iterator

	// use in_iter to read cin storing what we read in vec
	while (in_iter != eof)  // while there's valid input to read
		// postfix increment reads the stream and 
		// returns the old value of the iterator
		// we dereference that iterator to get 
		// the previous value read from the stream 
		vec.push_back(*in_iter++);

	// use an ostream_iterator to print the contents of vec
	ostream_iterator<int> out_iter(cout, " ");
	copy(vec.begin(), vec.end(), out_iter);
	cout << endl;

	// alternative way to print contents of vec
	for (auto e : vec)
		*out_iter++ = e;  // the assignment writes this element to cout
	cout << endl;
	system("pause");

}




反向迭代器(reverse iterator):這些迭代器向後而不是向前移動,除了firward_list以外的標準庫都有反向迭代器;input

移動迭代器(move iterator):這些專用的迭代器不是拷貝其中的元素,而是移動它們。

相關文章
相關標籤/搜索