C++ 将向量元素移动到向量的后面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23789498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:32:38  来源:igfitidea点击:

Moving a vector element to the back of the vector

c++vectorstdvector

提问by Violet Giraffe

Is there any better way (either faster or with fewer symbols of code) than erasing the element and re-adding it to the back?

有没有比擦除元素并将其重新添加到后面更好的方法(更快或使用更少的代码符号)?

template <typename T>
void moveItemToBack(std::vector<T>& v, size_t itemIndex)
{
   T tmp(v[itemIndex]);
   v.erase(v.begin() + itemIndex);
   v.push_back(tmp);
}

回答by Blastfurnace

You can do this with std::rotatefrom the standard library. Since this doesn't change the vector size it also won't trigger a reallocation. Your function would look something like this:

您可以std::rotate从标准库中执行此操作。由于这不会改变矢量大小,因此也不会触发重新分配。你的函数看起来像这样:

template <typename T>
void moveItemToBack(std::vector<T>& v, size_t itemIndex)
{
    auto it = v.begin() + itemIndex;
    std::rotate(it, it + 1, v.end());
}

回答by Nikos Athanasiou

Possibly the fastest way, would be to swap it with the last element

可能是最快的方法,将它与最后一个元素交换

template <typename T>
void moveItemToBack(std::vector<T>& v, size_t itemIndex)
{
   std::swap(v[itemIndex], v.back()); // or swap with *(v.end()-1)
}

one operation!Ofcourse std::swaphas to work with T

一个操作!当然std::swap必须与T

回答by Brian

You can avoid the extra variable.

您可以避免额外的变量。

v.push_back(v[itemIndex]);
v.erase(v.begin() + itemIndex);

If you delete frequently from the middle of the vector and can rewrite your code so that it doesn't require random access, you may be able to improve efficiency by using a linked list (std::list) instead.

如果您经常从向量中间删除并且可以重写您的代码使其不需要随机访问,您可以通过使用链表 ( std::list)来提高效率。