vector迭代器的增减问题

 在The C++ Standard Libray, A Tutorial and Reference 中,讲到vector时,有这样的一个section "The Increment and Decrement Problem of Vector Iterators",

原文如下:

The use of the increment and decrement operators of iterators includesa strange problem. In
general, you can increment and decrement temporary iterators. However, for vectors and strings,
you typically can't. Consider the following vector example:
std::vector<int> coll;
...
//sort, starting with the second element
// - NONPORTABLE version
if (coll.size() > 1) {
coll.sort (++coll.begin(), coll.end());
}
Typically, the compilation of sort()fails. However, if you use, for example, a deque rather than
a vector, it will compile. It might compile even with vectors, depending on the implementation of
class vector.

The reason for this strange problem lies in the factthat vector iterators are typically implemented
as ordinary pointers. And for all fundamental data types, such as pointers, you are not allowed to
modify temporary values. For structures and classes, however, it is allowed. Thus, if the iterator is
implemented as an ordinary pointer, the compilationfails; if implemented as a class, it succeeds.
It always works with deques, lists, sets, and mapsbecause you can't implement iterators as
ordinary pointers for them. But for vectors, whether it works depends on the implementation.
Usually, ordinary pointers are used.But if, for example, you use a "safe version" of the STL, the
iterators are implemented as classes. To make your code portable you should not code as the
previous example, using vectors. Instead, you should use an auxiliary object:
std::vector<int> coll;
...
//sort, starting with the second element
// - PORTABLE version
if (coll.size() > 1) {
std::vector<int>::iterator beg = coll.begin();
coll.sort (++beg, coll.end());
}

 

究竟讲的是什么问题呢?

原文中所谓的“fundamental data types”其实就是基础数据类型,比如int,char...,原文提到,指针(pointer)也算是“fundamental data type”,而这种类型的数据如果作为临时值(temporary value),是不允许修改的。哪里来的临时值??

且看以下代码:

 1 int f(int val1)
 2 {
 3     return val1;
 4 }
 5 
 6 int g(int& val2)
 7 {
 8     return val2;
 9 }
10 
11 //...
12 f(10) // NO PROBLEM
13 g(f(10)) //ERROR

两个函数都返回一个int的值,而这个值,其实就是系统生成的临时变量的值。第12行调用f(10),没错误。但是,下一行,用f(10)的返回值作为参数引用传递给函数g(),系统报错。原因是f()返回的是一个临时值,这个值不能修改,不能引用。

同理,vector<Type>::begin()返回的是一个指针,而且是一个临时值,所以就不能修改。

posted @ 2013-03-15 12:09  祖卡  阅读(545)  评论(0)    收藏  举报