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?
I have 2 hints here.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With