c++ - 交换容器中两个迭代器的位置

标签 c++ stl

我想交换两个迭代器 firstsecond 在容器中的位置,并在运行后保持它们有效。此外,如果我有迭代器 other 指向与 first 相同的值,我也想保持它有效(保持它指向相同的值)。是否可以使用任何 STL 容器实现?

最佳答案

你试过交换它们吗?

#include <algorithm>

// ...

swap(first, second);

(在 C++0x 中,#include 显着较小的 header <utility> 就足够了。)

Moreover if I have iterator other pointing at the same value as first I want to keep it valid too (keep it pointing at the same value).

只需重新分配 other交换后:

swap(first, second);
other = first;

关于c++ - 交换容器中两个迭代器的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7023634/

相关文章:

c++ - std::remove_if 移除的元素到哪里去了?

c++ - deque.push_front() 给出错误 "expression must have class type"

c - C 的 std::unordered_set(int) 容器库

c# - 同一文件中的文本和二进制数据

c++ - 如何为特定类(如STL容器)的成员函数或变量创建别名

c++ - 使用 Bitwise 生成二​​进制数 (C++)

java - Android JNI native 代码中的 C++ 对象是否调用垃圾回收?

c++ - 'windows.h',其他平台呢?

android - SDL 下 Android OpenGL ES 渲染中不确定的不需要的额外三角形

c++ - 使用 boost::mpl 获取 vector 的大小