简体   繁体   中英

get all vector elements greater than a value c++

I have a vector of float like:

vector<float> v = [0.4 0.2 0.8 0.1 0.5 0.6];

I would like to create a new vector (call it target):

vector<float> target;

containg only those elements greater than 0.5. I tried this line from this post

copy_if(v.begin(), v.end(), back_inserter(target), bind(less<float>(), 0.5, placeholders::_1));

but when I try to print out the elements in target, I obtain always the first element for n times (with n number of element inside v greater than 0.5).

the print is done in this way:

for (auto i = target.begin(); i != target.end(); ++i) {
    cout << target[*i] << endl;
}

Thanks in advance.

In your output, i is an iterator. target[*i] will print the element at the position equal to the element at i 's position. Since your values are all less than 1 and greater than 0, *i always equals 0. This leads to printing the element as position 0 a number of times equal to the number of elements in your vector.

Try the following instead :

for (auto i = target.begin(); i != target.end(); ++i) {
    cout << *i << endl;
}

Or simply :

for (auto i : target) {
    cout << i << endl;
}

You can use lambda to do it easily

#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;

int main()
{ 
   vector<float> v {0.4,0.2,0.8,0.1,0.5,0.6};
   vector<float> target;
   copy_if(v.begin(), v.end(), back_inserter(target),[](float n ){ return  n > 0.5;});
   for (auto i = target.begin(); i != target.end(); i++) {
    cout << *i << endl;
}
}

Output

0.8
0.6

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM