PhiloRobotist
PhiloRobotist

Reputation: 337

selecting elements of c++ vector by passing boolean values of whether to pick an index

In python, we can select a subset of an array by passing boolean values of whether to include the value at an index or not by:

import numpy as np
a=np.array([1,2,3,4,5,6])
b=a[np.array([False, True, True,False, True, True])
print(b) # prints array([2, 3, 5, 6])

Is there a C++ equivalent for this?

Upvotes: 0

Views: 646

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38341

Yes, there is a C++ equivalent: std::copy_if.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int func1() {
    std::vector<int> from_vector = {1,2,3,4,5,6};
    std::vector<int> to_vector;

    std::copy_if(from_vector.begin(), from_vector.end(),
        std::ostream_iterator<int>(std::cout, " "),
        [](int x) { return x % 3 != 1; });  // prints 2, 3, 5, 6

    std::copy_if(from_vector.begin(), from_vector.end(),
        std::back_inserter(to_vector),
        [](int x) { return x % 3 != 1; });
    // to_vector contains {2, 3, 5, 6}
}

//
// A bit closer equivalent to the code in the question.
// @user4581301: A great example of how not to translate Python to C++.
//

#include <deque>

int func2() {
    std::vector<int> from_vector = {1,2,3,4,5,6};
    std::deque<bool> filter = {false, true, true, false, true, true};
    std::vector<int> to_vector;

    std::copy_if(from_vector.begin(), from_vector.end(),
        std::ostream_iterator<int>(std::cout, " "),
        [&filter](int x) {
            if (filter.empty()) return false;
            const bool rv = filter.front();
            filter.pop_front();
            return rv;
        });  // prints 2, 3, 5, 6

    std::copy_if(from_vector.begin(), from_vector.end(),
        std::back_inserter(to_vector),
        [&filter](int x) {
            if (filter.empty()) return false;
            const bool rv = filter.front();
            filter.pop_front();
            return rv;
        });
    // to_vector contains {2, 3, 5, 6}
}

Upvotes: 2

Related Questions