count_if外部价值比较
comparison of external value in count_if
我想遍历一个向量,并希望在另一个向量中获取更大的元素计数。我在下面的代码片段中尝试过,不幸的是它不能以这种方式工作。
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<>());
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 在函数内部的声明中初始化数组,并在外部使用它
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- 使外部项目可用于find_package CMake
- C++将目录中的所有文件与::filesystem进行比较
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- count_if外部价值比较
- STD ::设置比较器,该比较器指的是外部值
- 取决于外部值的自定义比较器
- 将比较运算符"运算符<"实现为成员函数或外部函数
- c++ STL集合:比较对象与外部状态