Max_element with lambda:如何编译

max_element with lambda: how to compile?

本文关键字:何编译 编译 element with lambda Max      更新时间:2023-10-16

我正在学习一些新的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)

如何修复此编译错误?

这里有两个提示。

<标题> 语法错误
std::cout << *std::max_element(numbers.begin(), numbers.end(), [](int a, int b) { return a < b;}) << std::endl;

注意 *操作符。你需要它,因为max_element返回一个迭代器,所以为了打印值,你必须遵从它。

过时的编译器版本

您正在尝试使用现代c++ 功能与太旧的编译器。我建议你升级一下。无论如何,您可以使用当前编译器的版本,您只是将标志-std=c++0x添加到编译器命令。但从你的问题来看,可能默认情况下标志是启用的