我是C++的新手。
我正在尝试找到如何迭代遍历向量,以将每个元素与其他每个元素进行比较,其中比较顺序是不相关的,即;
(a 'compared to' b) = (b 'compared to' a)
因此,检查一个元素意味着您不需要将每个值与EVERY其他值进行比较,而只需比较其余值。
我有一个类似于这个TOY算法的东西;
#include <vector>
typedef std::vector<double> vector_t;
int countTheFoo(const vector_t &v)
{
int fooFound {0};
for (auto it1 = v.begin(); (it1 != v.end()); it1++)
{
for (auto it2 = it1.next(); (it2 != v.end()); it2++)
{
if testForFoo(*it1, *it2)
{
// Woot! Found some...
fooFound++;
}
}
}
return fooFound;
}
vector_t foo { 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0 };
int numFoo {countTheFoo(foo)};
我实际上是在比较线条,找到相交的线条而不是简单的重复线条,但技术方法是一样的。
这就是;
for (auto it2 = it1.next(); (it2 != v.end()); it2++)
我认为可以使用lambda表达式更高效地完成以下部分。
这种方法是可行的,但是:
在进行此类迭代时,它是否是最有效的方式?
是否可以使用std::for_all()将其作为lambda实现?
谢谢。