任何好的函数都可以用来移动容器中的元素
Any good function can be used to move an element in a container?
例如,我有一个向量,我想把位置1的元素移动到新位置3。
std::vector<int> v;
for (int i = 0; i < 5; ++i)
v.push_back(i);
// move element at position 1 to 3
// old vector: 0 1 2 3 4
// after move: 0 2 3 1 4
使用std::rotate
std::rotate( v.begin() + 1, v.begin() + 2, v.begin() + 4 );
// ^^^^^ 1 ^^^^^ 2 ^^^^^ 3
// 1 - beginning of the range to rotate - points to '1'
// 2 - element that will be brought to beginning after rotation - points to '2'
// 3 - one past end of range to rotate - points to '4'
使用旋转算法。
可以使用两次std::swap
std::swap(v[1], v[2]);
std::swap(v[2],v[3]);
给定0 1 2 3 4
第一交换:
0 2 1 3 4
第二次交换
0 2 3 1 4
你得到你想要的
如果指定范围[i,j]
,则可以将其放入函数中,并通过循环v[i]
到v[j]
来应用swap
相关文章:
- 为什么复制而不是移动数据元素?
- 设计将引用元素移动到开头的数据结构.C++
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 如何将数组中的元素向右移动?
- 在同一容器中移动元素
- 移动数组C++中的特定元素
- C++:我可以重用/移动 std::list 元素从中间到结尾吗?
- 在数组的开头添加一个元素并移动其余元素,但保留大小
- 如何将 std::vector 的某些元素移动到向量中的新索引?
- boost multi_index - 如果元素类型仅支持移动语义,如何遍历它?
- 在 C++ 中移动数组元素
- 从标准容器中移动元素是否合法?
- 为什么我不能将元素移动到不可复制的向量中?
- 如何将 std::vector 中的元素移动 1
- 将列表元素移动到列表末尾的函数多次不起作用
- 将 vector<vector> 的最后一个元素移动到<int>开头
- 将数组的特定元素移动到新数组
- 在 C 和 C++ 中,如何将数组中的某些元素移动到新数组中
- 我可以将一个QObject数组的单个元素移动到另一个QThread吗
- 将向量元素移动到向量的后面