我正在尝试比较 2 个大 vector (整数),即在每个条目处,查看两个 vector 是否具有相同的元素。我尝试了一些东西,使用迭代器进行比较和简单的 for 循环。两者都有效,但我需要一些可以加快速度的东西,因为我必须比较很多 vector 。在 C++ 中做到这一点的最佳方法是什么?非常感谢!
typedef vector<int> fingerprint;
double aakernel(fingerprint a,fingerprint b, double h){
double diff = 0;
vector<int>::iterator dd = a.begin();
vector<int>::iterator ee = b.begin();
for(; dd != a.end() && ee != b.end() ;++dd, ++ee){ /*option one*/
if (*dd!=*ee){
diff++;
}
}
for (int dd=0;dd<int(a.size());dd++){ /*option two*/
if (a[dd]!=b[dd]){
diff++;
}
}
double due = (h/(1-h));
double q = -log(due)*diff;
double K = exp(q);
return (K);
}
最佳答案
如果 vector 在其他方面是任意的,那么您无法比按顺序比较所有元素(就像您现在所做的那样)渐近地更好。所以你只剩下微优化,这可能会或可能不会提高性能(取决于你的编译器的优化器如何处理它们)。
我唯一能想到的就是将不变的评估从循环中移除。 (也许也不会在 double
类型上使用 ++
,但我相信编译器无论如何都会以最佳方式处理这个问题):
double diff = 0;
for (
auto itA = a.begin(), itB = b.begin(), endA = a.end();
itA != endA;
++itA, ++itB
) {
if (*itA != *itB) {
diff += 1.0;
}
}
关于c++ - 计算两个长 vector 中不同元素的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19902172/