任何好的函数都可以用来移动容器中的元素

Any good function can be used to move an element in a container?

本文关键字:元素 移动 函数 都可以 任何好      更新时间:2023-10-16

例如,我有一个向量,我想把位置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