我很好奇,为什么在我的例子中使用 lambda 函数的实现比使用等效对象的实现快得多。 为了让您了解规模:对于 10^4 的值,快的需要不到一秒,慢的需要几十秒。对于 10^5 个值,快的仍然会在一秒内完成,但慢的需要几分钟。
我想对两个数组的值进行排序,就像对其中一个数组进行排序一样。举个例子更容易理解: [5 1 2 0] 变为 [0 1 2 5] [3 5 6 7] 到 [7 5 6 3]
互联网上有多种方法可以做到这一点,但这不是我想问的。 我做了两种实现:一种使用带有重载 operator() 的对象,另一种使用 lambda 函数作为“比较”。
下面的代码没有注释 lambda 函数版本。要使用比较对象,只需注释掉“compare using lambda function”中的内容并取消注释“compare using compare object”即可。
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
void sortTwoVectorsByFirstVector(std::vector< float >& sortBySelf, std::vector< float >& sortByOther)
{
// init sort indices
std::vector < uint32_t > sortIndices(sortBySelf.size());
for (uint32_t i = 0; i < sortIndices.size(); ++i) {
sortIndices[i] = i;
}
//******** begin: compare using compare object
// struct CompareClass {
// std::vector< float > m_values;
// inline bool operator()(size_t i, size_t j)
// {
// return (m_values[i] < m_values[j]);
// }
// } compareObject { sortBySelf };
// std::sort(sortIndices.begin(), sortIndices.end(), compareObject);
//******* end: compare using compare object
//******** begin: compare using lambda function
std::sort(sortIndices.begin(), sortIndices.end(), [&sortBySelf](size_t i, size_t j) {return sortBySelf[i] < sortBySelf[j];});
//******** end: compare using lambda function
// collect the sorted elements using the indices
std::vector< float > sortedBySelf_sorted;
std::vector< float > sortByOther_sorted;
sortedBySelf_sorted.resize(sortBySelf.size());
sortByOther_sorted.resize(sortBySelf.size());
for (uint32_t i = 0; i < sortBySelf.size(); ++i) {
sortedBySelf_sorted[i] = sortBySelf[sortIndices[i]];
sortByOther_sorted[i] = sortByOther[sortIndices[i]];
}
sortBySelf.swap(sortedBySelf_sorted);
sortByOther.swap(sortByOther_sorted);
}
float RandomNumber()
{
return std::rand();
}
int main()
{
int vectorSize = 100000;
std::vector< float > a(vectorSize);
std::vector< float > b(vectorSize);
std::srand(100);
std::generate(a.begin(), a.end(), RandomNumber);
std::generate(b.begin(), b.end(), RandomNumber);
std::cout << "started" << std::endl;
sortTwoVectorsByFirstVector(a, b);
std::cout << "finished" << std::endl;
}
如果有人能弄清楚这种巨大的性能差距从何而来,那就太好了。
最佳答案
您手动编写的类复制了vector
:
std::vector< float > m_values; //<< By value
lambda 表达式只是引用它:
[&sortBySelf](size_t i, size_t j) {return sortBySelf[i] < sortBySelf[j];}
如果您通过拷贝获取 sortBySelf
(没有 &
),那么它们可能会有相似的性能。
关于c++ - 为什么 C++ Lambda 函数作为比较函数比等效对象快得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111673/