保留std :: vector的前N个元素。并删除其余的 [英] Keeping the first N elements of a std::vector<> and removing the rest

查看:2096
本文介绍了保留std :: vector的前N个元素。并删除其余的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

我尝试过:

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

其中 kpts 是我的向量,表现太恐怖了!大概是因为擦除的操作方式。

where kpts is my vector, and the performance is horrible! Presumably because of the way erase operates.

有没有办法只保留向量的前 50 个元素?似乎应该很明显,但是我找不到解决办法。

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

推荐答案

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

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

参见此处: 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

这篇关于保留std :: vector的前N个元素。并删除其余的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆