문제

I want to make a decreasing string sort in a set using lambda expression, but I don't know why I've got this error: "error C3497: you cannot construct an instance of a lambda". Can anyone help me, please.

#include <set>
#include <iostream>
#include <iterator>
#include <string>
#include <functional>

using namespace std;
typedef set<string, greater<string> > DecreasingStringSet;

int main()
{
    //lambda expression
    auto comp = [](string x, string y){ return x > y; };
    set< string , decltype(comp) > s(comp);
    s.insert("one");
    s.insert("two");
    s.insert("three");
    s.insert("four");
    for (auto x : s){
        cout << x << " ";
    }
    cout << endl;
    return 0;
}
도움이 되었습니까?

해결책

As mentioned by Manu above, the type of a lambda is unspecified. However, you can wrap it up in a std::function:

set< string, std::function<int(string x, string y)>> s(comp);

Incidentally, this sort of sorting predicate should 1) have const parameters (because you shouldn't be modifying the items being sorted during that sort) and 2) should be ref parameters if they're objects... as normal value parameters you'll be doing an awful lot of unnecessary copying, which will make thing inefficient.

Use this instead:

auto comp = [](const string&  x, const string&  y){ return x > y; };
set< string, std::function<int(const string& x, const string&  y)>> s(comp);

다른 팁

You already had the solution:

using namespace std;
typedef set<string, greater<string> > DecreasingStringSet;

int main()
{
    DecreasingStringSet s;

That's it. See it Live ON Coliru

It will be a lot more efficient than the lambda/std::function<> approach, plus it results in a class that is default constructible.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top