在C ++中根据布尔向量选择向量中的对象

时间:2019-03-08 17:00:02

标签: c++ c++14 stdvector

我有一个布尔向量(例如 true,true,false,false)和另一个大小相同但类型不同的向量。 我想要一个输出向量,其中第二个向量的元素与第一个向量中的true相对应。

基本上,我试图通过以下方式重现Julia或R中的内容:

vec = vec[to_select]

我试图编写一个copy_if,但是,好吧,假设编译器不太喜欢它。这就是我所拥有的

  auto it = copy_if(vec.begin(), vec.end(), to_select.begin(), vec.begin(), [](auto& val, auto& cond){return cond;});

然后调整大小:

vec.resize(std::distance(vec.begin(), it));

有没有建议以干净快速的方式做到这一点,可能不需要创建新的载体?

1 个答案:

答案 0 :(得分:2)

向量保证了连续的元素。因此,在计算保留标志序列中的偏移量时,可以通过在元素上使用指针运算来使用删除/擦除习惯用法:

#include <vector>
#include <algorithm>
int main()
{
    std::vector<int> vec = { 1,2,3,4,5,6,7,8 };
    std::vector<bool> flags = { true, true, true, false, true, false, false, true };

    vec.erase(std::remove_if(std::begin(vec), std::end(vec),
        [&](int& arg) { return !flags[&arg - vec.data()]; }), vec.end());

    for (auto x : vec)
        std::cout << x << ' ';
    std::cout.put('\n');
}

输出

1 2 3 5 8

很显然,vecflags的大小必须相同(更确切地说,flags至少与vec一样大)。