Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max_element with lambda: how to compile?

I am learning some new C++ features and couldn't get the following code compiled.

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> numbers;
    numbers.push_back(1);
    numbers.push_back(5);
    numbers.push_back(3);
    numbers.push_back(9);
    numbers.push_back(10);
    numbers.push_back(8);

    std::cout << std::max_element(numbers.begin(), numbers.end(), [](int a, int b) { return a < b;}) << std::endl;
    return 0;
}

My gcc version:

$ gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

The output when I try to compile:

$ g++ test_max_element.C 
test_max_element.C: In function ‘int main()’:
test_max_element.C:15:99: warning: lambda expressions only available with -std=c++0x or -std=gnu++0x [enabled by default]
test_max_element.C:15:100: error: no matching function for call to ‘max_element(std::vector<int>::iterator, std::vector<int>::iterator, main()::<lambda(int, int)>)’
test_max_element.C:15:100: note: candidates are:
/usr/include/c++/4.6/bits/stl_algo.h:6229:5: note: template<class _FIter> _FIter std::max_element(_FIter, _FIter)
/usr/include/c++/4.6/bits/stl_algo.h:6257:5: note: template<class _FIter, class _Compare> _FIter std::max_element(_FIter, _FIter, _Compare)

How can I fix this compilation error?

like image 908
user180574 Avatar asked Oct 21 '25 22:10

user180574


1 Answers

I have 2 hints here.

Syntax Error

std::cout << *std::max_element(numbers.begin(), numbers.end(), [](int a, int b) { return a < b;}) << std::endl;

Note the * operator. You need it because max_element returns an iterator, so in order to print the value you have to deference it.

Obsolete Compiler Version

You're trying to using a modern C++ features with a too old compiler. I suggest you to upgrade it. Anyway you can use the current compiler's version you have just add the flag -std=c++0x to the compiler command. But seeing from your question probabily the flag is enable by default.

like image 141
BiagioF Avatar answered Oct 24 '25 13:10

BiagioF