gpt4 book ai didi

c++ - vector 迭代器的增量/减量

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:43 24 4
gpt4 key购买 nike

Nicolai Josuttis 的“C++ 标准库”

第 9 章:STL 迭代器指出:

以下可能无法在某些平台上编译:

std::vector <int> coll;

//sort, starting with second element
//- NONPORTABLE version

if (coll.size() > 1){
std::sort(++coll.begin(),col.end());
}

Depending on the platform, the compilation of ++col.begin() might fail. However, if you use for example, a deque rather than a vector, the compilation always succeeds. ... ... utility function next() and prev() are provided with C++11 to account for code portability.

有人可以解释一下这种行为吗?

我在 MINGW gcc 4.6.1、Windows 操作系统上获得了正确的输出:

std::vector<int> coll ;
for (int i=15; i>=1; i--)
coll.push_back(i);

sort(++coll.begin(),coll.end());

最佳答案

Josuttis 很好地解释了这个潜在问题的原因:

The reason for this strange problem lies in the fact that iterators of vectors, arrays, and strings might be 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, doing so is allowed.

换句话说,这完全取决于std::vector<int>::iterator被定义为一个类或只是一个 typedef对于 int* .标准允许这两种情况,这就是为什么它可能会在某些编译器上引起问题,但不会在其他编译器上引起问题。

当您调用 coll.begin() 时右值 std::vector<int>::iterator被 build 。如果std::vector<int>::iterator是一个带有已实现前缀 operator++ 的类然后允许修改右值,因此它将编译。然而,它std::vector<int>::iterator是指向 int 的指针的 typedef,它是基本类型的右值,因此可能无法编译。

关于c++ - vector 迭代器的增量/减量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17764208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com