我正在学习一些新的C++功能,无法编译以下代码。
#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;
}
我的gcc版本:
$ 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.
我尝试编译时的输出:
$ 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)
如何解决此编译错误?
最佳答案
我在这里有2条提示。
语法错误
std::cout << *std::max_element(numbers.begin(), numbers.end(), [](int a, int b) { return a < b;}) << std::endl;
注意*
运算符。您需要它,因为max_element
返回一个迭代器,因此要输出该值,您必须遵循它。过时的编译器版本
您正在尝试将现代C++功能与过旧的编译器一起使用。我建议您升级它。
无论如何,您都可以使用当前编译器的版本,只需将标记
-std=c++0x
添加到编译器命令中即可。但是从您的问题来看,该标志默认是启用的。关于c++ - 带有lambda : how to compile?的max_element,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38840034/