Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill std::vector with data from another vector that meets some criteria

Tags:

c++

stl

vector

I have a vector of points, and I need to get those which are at a distance less than a value from a given point.

I could do it with a simple loop, but is there a better way to do it?

Thanks in advance

like image 226
MikMik Avatar asked Nov 30 '22 10:11

MikMik


1 Answers

Use std::remove_copy_if:

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

int main() {
    std::vector<int> v;
    v.push_back(3);
    v.push_back(2);
    v.push_back(6);
    v.push_back(10);
    v.push_back(5);
    v.push_back(2);
    std::vector<int> v2;

    std::remove_copy_if(v.begin(), v.end(), back_inserter(v2),
            std::bind2nd(std::greater<int>(),5));

    std::copy (v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout));
    std::cout << std::endl;
    return 0;
}

remove_copy_if will copy a sequence to an output iterator for each item which fails a predicate. In this case, the predicate is "x>5". There doesn't seem to be an equivalent copy_if for each item which passes a predicate test, but you can always negate a predicate with std::not1.

like image 189
Philip Potter Avatar answered Dec 04 '22 13:12

Philip Potter