count_if外部价值比较

comparison of external value in count_if

本文关键字:比较 外部 if count      更新时间:2023-10-16

我想遍历一个向量,并希望在另一个向量中获取更大的元素计数。我在下面的代码片段中尝试过,不幸的是它不能以这种方式工作。

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); });
}

如果你想计算vec2中有多少元素大于vec1中的i'th个元素,那么你的做法是正确的,只需要在lambda中捕获val

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); });
}

但是,如果要将vec2中的每个元素与vec1中的相应元素进行比较,则必须手动执行此操作。

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;
}

编辑: 正如@Jarod42评论的那样。可以在第二种情况下使用算法

auto res = std::transform_reduce(begin(vec2), end(vec2), begin(vec1), 0,
std::plus<>(), std::greater<>());