c++ - Create a new vector with some indices, potentially non-consecutive, dropped
问题描述
I have a std::vector<int>
of a certain size, and two numbers int a
and int b
, which could be non-consecutive. My intention is to get a new vector which has the same entries as the original, except for the indices a
and b
, which should be dropped. I need both vectors for further calculations.
At the moment I'm doing the following:
std::vector<int> old_vector = ...;
int a = ...;
int b = ...;
std::vector<int> new_vector;
for (int i = 0; i < old_vector.size(); i++) {
if (i != a && i != b) {
new_vector.push_back(old_vector[i]);
}
}
Is there a better way to do this?
解决方案
最惯用的方法是使用std::copy_if
lambda 作为谓词。
通常,如果可能,您希望使用标准库 (STL) 中的函数来表达您的解决方案。优点是熟悉 STL 的每个人都知道该函数的作用,并立即了解您要做什么。
但是,您的解决方案是完全有效的。
推荐阅读
- dns - 购买域名后 SSL 证书出现问题
- asp.net - 如何根据调查应用程序的数据库字段添加不同的控件?
- c++ - 扩展光标长度 QLineEdit?
- sql - xml.exist - sql:要排序的列
- android-studio - 如何让 Android Studio 自动将 proguard 映射文件包含在签名包中?
- python - 在 Python 中转置时如何维护复杂 ndarray 的虚部?
- javascript - 如何从 React / Typescript 应用程序中的选择选项中获取附加数据
- sql - AWS Redshift:获取 DATE 列的值时出错。考虑改用 TIMESTAMP 类型
- javascript - 如何从 google-cloud-firestore 获取数据到全局变量?
- java - 软件导致连接中止:KerberosRestTemplate (spring-security-kerberos-client) 的套接字写入错误