Get all positions of elements in STL vector that are greater than a value

前端 未结 3 1271
醉话见心
醉话见心 2020-12-31 18:39

I would like to know how can I find the index positions of elements that verify a certain condition (for example greater than). For example if I have a vector of int values<

3条回答
  •  长发绾君心
    2020-12-31 19:29

    I think I'd use std::copy_if:

    std::vector x{3, 2, 5, 8, 2, 1, 10, 4, 7};
    std::vector y(x.size());
    
    std::iota(y.begin(), y.end(), 0);
    std::copy_if(y.begin(), y.end(), 
                 std::ostream_iterator(std::cout, " "), 
                 [&](size_t i) { return x[i] > 5; });
    

    For me, this gives 3 6 8, the indices of 8, 10 and 7 in x -- exactly what we want.

    If you're stuck with a C++98/03 compiler/library, you'll use std::remove_copy_if instead (and reverse the sense of the comparison). In this case, you obviously won't be able to use a lambda for the comparison either.

提交回复
热议问题