C++ 使用lambda按降序创建字符串集
我想使用lambda表达式对集合进行递减字符串排序,但我不知道为什么会出现这样的错误:“错误C3497:您无法构造lambda的实例”。谁能帮帮我吗C++ 使用lambda按降序创建字符串集,c++,lambda,C++,Lambda,我想使用lambda表达式对集合进行递减字符串排序,但我不知道为什么会出现这样的错误:“错误C3497:您无法构造lambda的实例”。谁能帮帮我吗 #include <set> #include <iostream> #include <iterator> #include <string> #include <functional> using namespace std; typedef set<string, great
#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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
类型定义设置递减字符串集;
int main()
{
//lambda表达式
自动编译=[](字符串x,字符串y){返回x>y;};
设置s(comp);
s、 插入(“一”);
s、 插入(“两个”);
s、 插入(“三”);
s、 插入(“四”);
用于(自动x:s){
cout如上所述,lambda的类型未指定。但是,您可以将其封装在std::function
:
set< string, std::function<int(string x, string y)>> s(comp);
sets(comp);
顺便说一句,这种排序谓词应该1)具有常量参数(因为您不应该在排序期间修改要排序的项),2)如果它们是对象,则应该是ref参数……作为正常值参数,您将执行大量不必要的复制,这将使事情效率低下
改用这个:
auto comp = [](const string& x, const string& y){ return x > y; };
set< string, std::function<int(const string& x, const string& y)>> s(comp);
auto comp=[](常量字符串&x,常量字符串&y){return x>y;};
设置s(comp);
您已经有了解决方案:
using namespace std;
typedef set<string, greater<string> > DecreasingStringSet;
int main()
{
DecreasingStringSet s;
使用名称空间std;
类型定义设置递减字符串集;
int main()
{
减小字符串集s;
就是这样。看到了吗
它将比lambda/std::function
方法效率更高,而且会产生一个默认可构造的类。您使用的编译器是什么?它在这里工作:对我来说。lambda的类型是未指定的(好的,它只是由编译器生成的一个函子,但它是未指定的函子)所以像decltype(lambda)
这样的表达式是不可能的。我使用的是visual studio 2012的编译器,我在VS2013下也会遇到这个错误。但出于某种原因,它在GCC 4.7下工作。这是一个报告的错误,他们说:“……我们可能没有时间在VC12中修复它…”好的,就是这样,谢谢。是的,在GCC上工作很好,也谢谢。@user3456848“好的,就是这样,谢谢。是的,在GCC上工作很好,也谢谢”所以为什么不接受这个答案呢?