gpt4 book ai didi

c++ - 在 C++ 中用 lambda 替换函数

转载 作者:行者123 更新时间:2023-11-27 22:35:18 25 4
gpt4 key购买 nike

我有一个函数,它只是将值 1 设置为结构成员变量 length。在现代 C++ 中,这似乎不是好的代码风格。这可以用 lambda 来完成吗?

void setEdgeLengths(Koala::AssocArray <koalaGraph::PEdge, Koala::DijkstraHeap::EdgeLabs<int >> &edgeMap, std::vector<koalaGraph::PEdge>& E) 
{
for (size_t i = 0; i < E.size(); i++) {
edgeMap[E[i]].length = 1;
}
}

我问的原因是https://shaharmike.com/cpp/lambdas-and-functions/这表明 lambda 将比普通函数更快。

Lambdas are also awesome when it comes to performance. Because they are objects rather than pointers they can be inlined very easily by the compiler, much like functors. This means that calling a lambda many times (such as with std::sort or std::copy_if) is much better than using a global function. This is one example of where C++ is actually faster than C.

最佳答案

我认为以下代码是最佳的(除了给定的变量名):

void setEdgeLengths(Koala::AssocArray <koalaGraph::PEdge, Koala::DijkstraHeap::EdgeLabs<int >> &edgeMap, std::vector<koalaGraph::PEdge>& E) 
{
for (const auto& e : E) {
edgeMap[e].length = 1;
}
}

根据需要设计(或省略)花括号。

您可以将其中的任何一个或全部放入任意多个嵌套的 lambda 中,但这并不比添加更多空格更有用(但可能更有害,至少在调试版本中是这样)。你可能想问的是:

void setEdgeLengths(Koala::AssocArray <koalaGraph::PEdge, Koala::DijkstraHeap::EdgeLabs<int >> &edgeMap, std::vector<koalaGraph::PEdge>& E) 
{
std::for_each(E.begin(), E.end(), [&edgeMap](const auto& e) {
edgeMap[e].length = 1;
});
}

您不再有一个简单的循环(有些人提倡这种循环是好的风格),但我认为代码并没有变得更清晰。这样做也没有加快速度 - 如果有的话,调试性能可能会略有降低。

现在,后一种形式确实允许并行执行

std::for_each(std::execution::parallel, E.begin(), E.end(), [&edgeMap](const auto& e) {

但这只有在您的 edgeMap 正确处理并发访问时才合法。如果它是一个 std::mapoperator[] 可能会插入一个新元素(这不是线程安全的),所以如果没有进一步的假设,这将是不合法的优化。

关于c++ - 在 C++ 中用 lambda 替换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55265653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com