在向量中移动项目

时间:2015-03-04 04:43:14

标签: c++

将向量中的项目从第4个位置移动到第2个位置的最有效方法是什么。在这种情况下,向量可以包含100个以上的元素。移动元素的算法应该基于迭代器或索引(意思是找到4元素(源)和第二元素(目标)),哪一个更好。我已经尝试过基于索引(What is the most effective way to move items within a vector?在我的情况下获取第4和第2位的迭代器比更容易计算指数。

1 个答案:

答案 0 :(得分:3)

我相信您可以使用std::rotate

vector<T> vec = ...
vector<T>::iterator from = ...
vector<T>::iterator to = ...
if(from < to ) {
    rotate(from, from+1, to+1);
} else if (from > to) {
    rotate(to, from, from+1);
}

免责声明:未经测试的代码

顺便说一句,您可以使用例如

轻松地从迭代器获取矢量索引
vector<T> vec = ...
vector<T>::iterator it = ...
size_t idx = it - vec.begin();