[英]C++ how to use std::adjacent and std::count_if together, to count the number of occurrences of a condition in a vector
在 C++ 中,我有一个类成员函数,它采用对象向量。
从每两个连续的对象中,我创建一个 std::pair<unsigned, unsigned> (Level1, Level2)。
我想要做的是计算向量中 A 的对大于 B 的次数。
我试图用 std::count_if 来做到这一点,但它不接受谓词中的 2 个参数。
所以我开始不使用 std::adjacent_find。
我如何扩展我必须实际计算 A 对大于 B 的次数?
int mv::class::countOccurances(std::vector<OpListIterator>& sortedops)
{
std::adjacent_find(sortedops.begin(), sortedops.end(),
[](opListIterator a, opListIterator b){
std::pair<unsigned,unsigned> A (a->get<unsigned>("Level1"),a->get<unsigned>("Level2"));
std::pair<unsigned,unsigned> B (b->get<unsigned>("Level1"),b->get<unsigned>("Level2"));
return A > B;
});
}
好的,据我所知,这里的问题不在于定义较少的运算符,所以这里是示例解决方案。
int mv::class::countOccurances(const std::vector<OpListIterator>& sortedops)
{
std::count_if(sortedops.begin(), sortedops.end(),
[](const opListIterator& a, const opListIterator& b){
std::pair<unsigned,unsigned> A (a->get<unsigned>("Level1"),a->get<unsigned>("Level2"));
std::pair<unsigned,unsigned> B (b->get<unsigned>("Level1"),b->get<unsigned>("Level2"));
return ( A.first == B.first ? A.second < B.second : A.first < B.first);
});
}
首先为了简化,先介绍一下投影函数:
std::pair<unsigned, unsigned> projection(opListIterator it)
{
return { it->get<unsigned>("Level1"), it->get<unsigned>("Level2")};
}
你可能会用那个奇怪的谓词滥用std::adjacent_find
:
int count = 0;
std::adjacent_find(sortedops.begin(), sortedops.end(),
[&](opListIterator current, opListIterator next) {
count += projection(current) > projection(next);
return false; // never considered as equal
});
return count;
正确的使用方法是:
int count = 0;
auto it = sortedops.begin();
while (it != sortedops.end()) {
it = std::adjacent_find(it, sortedops.end(),
[&](opListIterator current, opListIterator next) {
return projection(current) > projection(next);
});
if (it != sortedops.end()) { ++count; ++it; }
}
return count;
对于std::count_if
,范围(ranges-v3 或 C++20)可能有帮助:
auto range = ranges::view::zip(sortedops, sortedops | ranges::view::drop(1)); // current/next pairs
return std::count_if(begin(range), end(range), [](const auto& p){
return projection(p.first) > projection(p.second);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.