从 C++ std::vector 中删除第 i 个项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4442477/
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 15:25:15  来源:igfitidea点击:

Remove ith item from a C++ std::vector

c++vector

提问by kralco626

How do I remove the ith item from a std::vector?

如何从 a 中删除第 i 个项目std::vector

I know I want to delete the ith element. I have int i; and std::vector<process> pList;where processis a struct. I want to do something equivalent to the following:

我知道我想删除第 i 个元素。我有一个结构int i; and std::vector<process> pList;在哪里process。我想做一些相当于以下的事情:

pList.remove(i);

回答by fredoverflow

Here is an O(1) solution, assuming you don't care about the order of elements:

这是一个 O(1) 解决方案,假设您不关心元素的顺序:

#include <algorithm>

// ...

{
    using std::swap;
    swap(pList[i], pList.back());
    pList.pop_back();
}

For PODs, assignment is faster than swapping, so you should simply write:

对于 POD,分配比交换更快,因此您应该简单地编写:

pList[i] = pList.back();
pList.pop_back();

In C++11, you can forget the above distinction and always use move semantics for maximum efficiency:

在 C++11 中,你可以忘记上面的区别并始终使用移动语义以获得最大效率:

if (i != pList.size() - 1)
{
    // Beware of move assignment to self
    // see http://stackoverflow.com/questions/13127455/
    pList[i] = std::move(pList.back());
}
pList.pop_back();

回答by Vladimir

pList.erase(pList.begin()+i);

To remove element with index i.

删除索引为 i 的元素。

回答by Nawaz

An approach to save yourself from linear complexity!

一种从线性复杂性中拯救自己的方法!

Since vector.erase() is linear complexity, I would suggest that just swap the ith element with the last element and thenerase the element at the end (which is actually ith element); that way, you possibly can save yourself from linear complexity. That is just my thought!

由于 vector.erase() 是线性复杂度,我建议只将第 i 个元素与最后一个元素交换,然后擦除末尾的元素(实际上是第 i 个元素);这样,您可能可以避免线性复杂性。这只是我的想法!

回答by Sanjit Saluja

Use Vector.Erase. The complexity is linear on the number of elements erased (destructors) plus the number of elements after the last element deleted (moving).

使用Vector.Erase。复杂性与删除(析构函数)的元素数量加上删除(移动)最后一个元素后的元素数量成线性关系。

iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );

回答by Tom Johnson

vector.erase(iterator)

Where iterator is the position. You can get the first element with vector.begin() and the last one with vector.end(). Just add to the iterator to get to the desired element. e.g.:

其中迭代器是位置。您可以使用 vector.begin() 获取第一个元素,使用 vector.end() 获取最后一个元素。只需添加到迭代器即可获得所需的元素。例如:

pList.erase(pList.begin()+6);

to erase the 6th item.

擦除第 6 项。