下面的代码产生什么

What does the following code produce?

本文关键字:什么 代码      更新时间:2023-10-16

我不知道这是不是一个技巧问题,但当我试图运行这段代码时,我会遇到一些错误。你认为老师忘了写#include行吗?

#include <iostream>
#include <vector>
using namespace std;
int display(int val) {
    cout << val << ",";
}
int main() {
    int a[] = {1, -4, 5, -100, 15, 0, 5};
    vector<int> v(a, a + 7);
    sort(v.begin(), v.end(), greater<int>());
    for_each(v.begin(), v.end(), display);
}

g++ -ggdb  -c test.cpp
test.cpp: In function 'int main()':
test.cpp:13:41: error: 'sort' was not declared in this scope
test.cpp:14:38: error: 'for_each' was not declared in this scope
make: *** [test.o] Error 1

感谢

你认为老师忘了写#include行吗?

他肯定忘了:

#include <algorithm>

这是std::sortstd::for_each等算法的标准库头,这正是编译器所抱怨的。

顺便说一句,尽管你的编译器还没有抱怨这一点,但他也忘记了:

#include <functional>

这是函数(如std::greater<>)的标准库头,您可以在这里使用它。

此外,您的(教师的?)display()函数的返回类型应该是void,因为它目前没有返回值。

是的,std::sortstd::for_each需要#include <algorithm>,这很可能是您在说sortfor_each时想要调用的。该算法的效果是按递增顺序对数组a进行排序,并将元素打印到stdout。