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

7
  • What compiler flags are you using? Commented Dec 8, 2016 at 14:34
  • 2
    you need to make your IDE or makefile to pass -std=c++11 or -std=c++0x parameter to compiler Commented Dec 8, 2016 at 14:37
  • 1
    It looks like lambdas aren't supported in GCC 4.4. Commented Dec 8, 2016 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. Commented Dec 8, 2016 at 15:12
  • 1
    @N.Ramos I highly suggest you read about C++ functors if that is the case Commented Dec 8, 2016 at 16:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Wrong compiler, GCC 4.4 doesn't support lambdas the OP will have to use a functor.
Thanks -- updating answer
using ubuntu and gCC
gCC will not compile C++ constructs -- you will need to use g++

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.