【发布时间】:2016-12-08 12:54:21
【问题描述】:
下面的代码在 Visual Studio 中排序成功。
但是,在 Ubuntu GCC 4.4.7 编译器会抛出错误。似乎对这种语法并不熟悉。
我该如何修复这一行以使代码在 GCC 中工作? (编译器是远程的。所以我也无法升级 GCC 版本)。
我在这里做的是:根据它们的适应度值对向量 B 元素进行排序
//B is a Vector of class Bird
//fitness is a double - member of Bird objects
vector<Bird> Clone = B;
sort(Clone.begin(), Clone.end(), [](Bird a, Bird b) { return a.fitness> b.fitness; });
//error: expected primary expresssion before '[' token
//error: expected primary expresssion before ']' token...
(注意:这 3 行代码在 MSVC 中编译成功,但在 GCC 中编译失败)
我的回答是
bool X_less(Bird a, Bird b) { return a.fitness > b.fitness; }
std::sort(Clone.begin(), Clone.end(), &X_less);
它似乎工作。它是一个功能还是没有?我不知道它的技术名称,但它似乎工作。我对 C++ 不太熟悉。
【问题讨论】:
-
你使用什么编译器标志?
-
你需要让你的IDE或makefile将
-std=c++11或-std=c++0x参数传递给编译器 -
在 GCC 4.4 中看起来像 lambdas aren't supported。
-
看来您有两个选择:在 Ubuntu 上获得更好的编译器或使用仿函数。 Lambda 不是一种选择。我还建议通过
const&获取比较参数,否则每次运行比较时都会复制它们。 -
@N.Ramos 我强烈建议你阅读C++ functors if that is the case