首页 > 解决方案 > 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?

标签: c++

解决方案


最惯用的方法是使用std::copy_iflambda 作为谓词。

通常,如果可能,您希望使用标准库 (STL) 中的函数来表达您的解决方案。优点是熟悉 STL 的每个人都知道该函数的作用,并立即了解您要做什么。

但是,您的解决方案是完全有效的。


推荐阅读