【问题标题】:Compiler Error on std::sort function (GCC 4.4)std::sort 函数上的编译器错误 (GCC 4.4)
【发布时间】: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&amp; 获取比较参数,否则每次运行比较时都会复制它们。
  • @N.Ramos 我强烈建议你阅读C++ functors if that is the case

标签: c++ c++11 lambda gcc4.4


【解决方案1】:

您需要升级您的 C++,因为 4.4 太旧,无法支持 Lambda。我有 Gcc 4.8,但它仍然需要您启用包含 lambda 函数的 c++11,所以

$ g++  -std=c++11  x.cc

编译得很好

#include <algorithm>
#include <functional>
#include <vector>

using namespace std;

int main()
{
    vector<int> Clone;

    sort(Clone.begin(), Clone.end(), [](int a, int b) { return a> b; });
}

但在没有-std=c++11 选项的情况下仍然会出错

【讨论】:

  • 错误的编译器,GCC 4.4 doesn't support lambdas OP 将不得不使用仿函数。
  • 谢谢——更新答案
  • 使用 ubuntu 和 gCC
  • gCC 不会编译 C++ 结构——你需要使用 g++
猜你喜欢
  • 2016-11-13
  • 2018-03-19
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
  • 1970-01-01
相关资源
最近更新 更多