以下代码产生了什么?

时间:2013-02-18 23:18:54

标签: c++

我不知道这是一个技巧问题还是什么,但是当我尝试运行这段代码时,我会遇到一些错误。你认为老师忘了输入#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

由于

2 个答案:

答案 0 :(得分:8)

  

你认为老师忘了输入#include一行吗?

他绝对忘了:

#include <algorithm>

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

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

#include <functional>

这是std::greater<>等仿函数的标准库标题,您可以在这里使用它。

此外,您的(教师?)display()函数应该有void作为返回类型,因为它当前不返回任何值。

答案 1 :(得分:5)

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