0

The code below sorting in Visual Studio successfully.
But, in Ubuntu GCC 4.4.7 compiler throws error. It seems it's not familiar with this type of syntax. How shall I fix this line to make code working in GCC? (the compiler is remote. So I can't upgrade the GCC version either). What I'm doing right here is:sorting Vector B elements regarding their fitness values

//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...

(Note: this 3 piece of lines compiling successful in MSVC but not in GCC)


my answer is
bool X_less(Bird a, Bird b) { return a.fitness > b.fitness; }

std::sort(Clone.begin(), Clone.end(), &X_less);

It seems to work. Is it a function or not? I don't know its technical name, but it seems to work. I am not much familiar with C++.

eddie
  • 1,252
  • 3
  • 15
  • 20
Zen Of Kursat
  • 2,672
  • 1
  • 31
  • 47
  • What compiler flags are you using? – Soren Dec 08 '16 at 14:34
  • 2
    you need to make your IDE or makefile to pass `-std=c++11` or `-std=c++0x` parameter to compiler – Slava Dec 08 '16 at 14:37
  • 1
    It looks like [lambdas aren't supported](https://gcc.gnu.org/gcc-4.4/cxx0x_status.html) in GCC 4.4. – Quentin Dec 08 '16 at 15:05
  • it appears you have two options: get a better compiler on Ubuntu or use a functor. Lambdas are not an option. I would also suggest taking the comparison parameters by `const&` otherwise you're making copies of them every single time the comparison is run. – Mgetz Dec 08 '16 at 15:12
  • Im using a remote Compiler farm of university. Im unable to change gcc 4.4 compiler – Zen Of Kursat Dec 08 '16 at 16:07
  • 1
    @N.Ramos I highly suggest you read about [C++ functors if that is the case](http://stackoverflow.com/q/356950/332733) – Mgetz Dec 08 '16 at 16:49
  • using a compiler namely gCCç parameters I attempted to use are -std=c++11 or -std=c++0x none of helped me to avoid this error. – Zen Of Kursat Dec 09 '16 at 21:17

1 Answers1

2

You will need to upgrade your C++ as 4.4 is too old to support Lambda. I have Gcc 4.8, but it still requires you enable c++11 that includes lambda functions, so

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

compiles this fine

#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; });
}

but still gives errors without -std=c++11 option

Soren
  • 14,402
  • 4
  • 41
  • 67