如何在C ++ 11中使用lambda auto参数

编程入门 行业动态 更新时间:2024-10-28 20:17:17
本文介绍了如何在C ++ 11中使用lambda auto参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个代码在C ++ 14。但是,当我在C ++ 11中使用它时,它在 const auto 中有一个错误。如何在C ++ 11中使用它?

I have a code in C++14. However, when I used it in C++11, it has an error at const auto. How to use it in C++11?

vector<vector <int> > P; std::vector<double> f; vector< pair<double, vector<int> > > X; for (int i=0;i<N;i++) X.push_back(make_pair(f[i],P[i])); ////Sorting fitness descending order stable_sort(X.rbegin(), X.rend()); std::stable_sort(X.rbegin(), X.rend(), [](const auto&lhs, const auto& rhs) { return lhs.first < rhs.first; });

推荐答案

C ++ 11不支持通用lambdas 。这就是lambda的参数列表中的 auto 实际代表:一个通用参数,可与一个函数模板中的参数相比。 (注意 const 在这里不是问题。)

C++11 doesn't support generic lambdas. That's what auto in the lambda's parameter list actually stands for: a generic parameter, comparable to parameters in a function template. (Note that the const isn't the problem here.)

你基本上有两个选项:

You have basically two options:

  • 输入正确类型而不是 。这里是 X 的元素类型,它是 pair< double,vector< int> 。如果你发现这个不可读,typedef可以帮助。

  • Type out the correct type instead of auto. Here it is the element type of X, which is pair<double, vector<int>>. If you find this unreadable, a typedef can help. std::stable_sort(X.rbegin(), X.rend(), [](const pair<double, vector<int>> & lhs, const pair<double, vector<int>> & rhs) { return lhs.first < rhs.first; });

  • 使用具有调用运算符模板的函数替换lambda >。这就是通用lambdas基本上在后台实现的方式。 lambda是非常通用的,所以考虑把它放在一些全局实用程序头。 (但是不要使用命名空间std; 但输入 std :: ,以防万一你把它放在一个标题。

  • Replace the lambda with a functor which has a call operator template. That's how generic lambdas are basically implemented behind the scene. The lambda is very generic, so consider putting it in some global utility header. (However do not using namespace std; but type out std:: in case you put it in a header.)

    struct CompareFirst { template <class Fst, class Snd> bool operator()(const pair<Fst,Snd>& l, const pair<Fst,Snd>& r) const { return l.first < r.first; } };

    std::stable_sort(X.rbegin(), X.rend(), CompareFirst());

  • 更多推荐

    如何在C ++ 11中使用lambda auto参数

    本文发布于:2023-10-09 00:00:35,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1474133.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:参数   如何在   lambda   auto

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!