C++ 保留 std::vector<> 的前 N ​​个元素并删除其余元素

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

Keeping the first N elements of a std::vector<> and removing the rest

c++vector

提问by Brett

I have a std::vector<int>variable in my C++application. The size of the vector is determined at runtime, but is typically about 1000.

std::vector<int>我的C++应用程序中有一个变量。向量的大小在运行时确定,但通常约为1000

I have sorted this vector (which works well), and after sorting, I would like to keep only the first 50elements.

我已经对这个向量进行了排序(效果很好),排序后,我只想保留第一个50元素。

I have tried:

我试过了:

kpts.erase(kpts.begin() + 50, kpts.end());

where kptsis my vector, and the performance is horrible! Presumably because of the way eraseoperates.

kpts我的矢量在哪里,性能太糟糕了!大概是因为erase操作方式。

Is there a way to only keep the first 50elements of a vector?It seems like it should be obvious, but I can't find a way to do this.

有没有办法只保留50向量的第一个元素?看起来应该很明显,但我找不到办法做到这一点。

回答by Moritz

Yes, you can use std::vector::resize, which just truncates if the length of the vector is greater than n.

是的,您可以使用std::vector::resize,如果向量的长度大于 n,它只会截断。

See here: http://www.cplusplus.com/reference/vector/vector/resize/

见这里:http: //www.cplusplus.com/reference/vector/vector/resize/

std::vector<int> myvector;

for (int i=1;i<1000;i++) myvector.push_back(i);

myvector.resize(50);
// myvector will contain values 1..50