I want to iterate through a vector and want to get count of greater elements in another vector. I tried below code snippet, unfortunately it does not work this way.
sort(begin(vec1),end(vec1));
sort(begin(vec2),end(vec2));
for(int i = 0; i < vec1.size(); i++)
{
int val = vec1[i];
count_if(begin(vec2),end(vec2),[](int x) { return (x > val); });
}
If you want to count how many elements in vec2
is greater than the i'th
element in vec1
then you are doing it correct and just have to capture val
in the lambda
for(int i = 0; i < vec1.size(); i++)
{
int val = vec1[i];
auto res = count_if(begin(vec2),end(vec2), [val](int x) { return (x > val); });
}
but if you want to compare each element in vec2
with the corresponding element in vec1
you have to do it manually.
int count = 0;
//here the sizes of vec1 and vec2 must be equal
for (auto it1 = begin(vec1), it2 = begin(vec2); it1 != end(vec1); ++it1, ++it2) {
if (*it2 > *it1)
++count;
}
EDIT: As @Jarod42 commented. It is possible to use an algorithm for the second case
auto res = std::transform_reduce(begin(vec2), end(vec2), begin(vec1), 0,
std::plus<>(), std::greater<>());
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.