简体   繁体   English

获取所有大于值的向量元素c ++

[英]get all vector elements greater than a value c++

I have a vector of float like: 我有一个像float的向量:

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. 仅包含大于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). 但是当我尝试打印目标中的元素时,我总是获得n次第一个元素(v内n个元素的数量大于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. 在您的输出中, i是一个迭代器。 target[*i] will print the element at the position equal to the element at i 's position. target[*i]将在等于i位置的元素的位置打印元素。 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. 由于您的值均小于1且大于0,因此*i始终等于0。这将导致元素在位置0的打印次数等于矢量中元素的数量。

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 您可以使用lambda轻松完成

#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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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