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