如何在C ++ 11中使用lambda auto参数 [英] How to use lambda auto parameters in C++11

查看:178
本文介绍了如何在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:


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

  1. 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参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆