Iterator Argument Types

C++ Primer 4/e在A First Look at the Algorithms这个地方有一个关键观念:‘In general, the generic algorithms operate on iterator pairs that denote a range of elements in a container (or other sequence). The types of the arguments that denote the range must match exactly, and the iterators themselves must denote a range: They must refer to elements in the same container (or to the element just past the end of that container), and if they are unequal, then it must be possible to reach the second iterator by repeatedly incrementing the first iterator.

Some algorithms, such as find_first_of, take two pairs of iterators. The iterator types in each pair must match exactly, but there is no requirement that the type of the two pairs match each other. In particular, the elements can be stored in different kinds of sequences. What is required is that we be able to compare elements from the two sequences.

In our program, the types of roster1 and roster2 need not match exactly: roster1 could be a list while roster2 was a vector, deque, or other sequence that we’ll learn about later in this chapter. What is required is that we be able to compare the elements from these two sequences using the == operator. If roster1 is a list<string>, then roster2 could be a vector<char*> because the string library defines == on a string and a char*.’

中文版的这样写:‘一般说来,泛型演算法作用于“用来标示容器元素(或其他序列)区间”的一对iterators身上。这两个iterators的型别必须完全相同,而且这两个iterators必须标示出一个有效区间:它们必须指向同一个容器(或容器末端的下一位置),而且当两个iterators不等时,重复累加第一个iterator必须可以到达第二个iterator。

某些演算法,例如find_first_of(),带有两对iterators。每一对的两个iterators的型别必须完全相同,但两对iterators彼此不必相同。更明确的说,被操作的所有元素可储存不同种类的序列中,只要两序列内的元素可进行比较就没问题。

因此,上述程式的roster1和roster2,其型别无须相同,roster1可以是个list而roster2可以是个vector、deque或其他序列(本章稍后会出现这种情况)。唯一必须保证的是,两序列内的元素必须可以使用==运算子比较是否相等。如果roster1是个list<string>,那么roster2可以是个vector<char *>,因为标准库为string和char *定义了一个==运算子。’

仅纪录之。