c++ - 交换时增量迭代器 std::next

标签 c++ stl iterator swap

考虑代码:

list<int> a{ 4,3,1,2 };
auto i = a.begin();
swap(*i, *(++i));

为什么交换什么都不做?虽然以下按预期工作?

list<int> a{ 4,3,1,2 };
auto i = a.begin();
swap(*i, *(next(i)));

最佳答案

在第一段代码中,*i*(++i) 这两个操作的求值顺序 unspecified after c++17 ,因此第二个可能在第一个之前执行,然后交换交换两个等价的值。

在附件中,你可以看到

f(++i, ++i); // undefined behavior until C++17, unspecified after C++17

但是在第二个代码中你有不同的参数并且 std::next() 返回一个新的迭代器。

关于c++ - 交换时增量迭代器 std::next,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63453741/

相关文章:

C++ 指针和数组

c++ - `std::bitset` 有和没有边界检查

java - 迭代实现 Iterable<Item> 的类中数组的非空部分

c++ - 重新分配 std::map::value_type& 是否安全?

c++ - OpenCV - 查找轮廓图像的高度和宽度

c++ - 从对象中获取项目集合的最佳实践?

c++ - 如何在 C++ 中使用右值引用来避免不必要的实例

c++ - 返回对 InputIterator 内部状态的引用是否合法?

c++ - (w)ifstream 是否支持不同的编码

c++ - std::string::iterator 的 Linux 段错误