且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-18 23:20:59

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());