Set std::vector elements under condition in c++

Hi People,

I want to do -in the best possible way- something like this python line, in c++ by means of std::vector

v1[v2 > 0] = 1

That is: For every v2 index in which v2 > 0, v1 element is set to 1 -for such index.

Where v1 and v2 are vectors of float elements, and
v1 is initialized to 0 in every element.

Thanks in advance
With std::valarray instead of std::vector, you can compile exactly that line in C++, except you have to use the floating-point zero to compare to a valarray of floating-point values (or else make v2 a valarray<int>)

1
2
3
4
5
6
7
8
9
10
11
12
#include <valarray>
#include <iostream>

int main()
{
    std::valarray<double> v1 = {0,0,0, 0, 0, 0,0,0,0};
    std::valarray<double> v2 = {1,2,3,-1,-2,-3,0,0,0};

    v1[v2 > 0.] = 1; // <-- here's your line

    for(double d : v1) std::cout << d << ' ';
}

demo http://coliru.stacked-crooked.com/a/f52da076ee66682b

With vectors though, you may have to write a plain loop walking the second vector and writing to the first.

Last edited on
oh, and if you want to see the future, with ranges (coming to C++ standard in 2020 or later) it could be done this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <vector>
#include <iostream>
#include <range/v3/all.hpp>
using namespace ranges::v3;
int main()
{
    std::vector<double> v2 = {1,2,3,-1,-2,-3,0,0,0};
    std::vector<double> v1(v2.size()); // 9 zeroes
    
    v1 = view::zip_with([](auto a, auto b){return b > 0 ? 1 : a;}, v1, v2);
    
    for(double d : v1) std::cout << d << ' ';
}

demo: http://coliru.stacked-crooked.com/a/4abdac7bad8e75a9
Last edited on
Thank you very much Cubbi,

Great answers!

Best,

Dario
Topic archived. No new replies allowed.