将向量中的项目从第 4 个位置移动到第 2 个位置的最有效方法是什么。这种情况下的向量可以包含 100 多个元素。移动元素的算法应该基于迭代器或索引(意思是找到第 4 个元素(源)和第 2 个元素(目标)),哪个更好。我已经根据索引尝试过(在向量中移动项目的最有效方法是什么?在我的情况下,获取第 4 个和第 2 个的迭代器位置比计算索引更容易。
相信你能用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);
}
Run Code Online (Sandbox Code Playgroud)
免责声明:未经测试的代码
顺便说一句,您可以轻松地从迭代器中获取向量索引,例如,
vector<T> vec = ...
vector<T>::iterator it = ...
size_t idx = it - vec.begin();
Run Code Online (Sandbox Code Playgroud)