2013-02-18 86 views
0

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

感谢

+4

在当你未来的错误,如这些,你可以搜索一个C++的参考,像我一样的[排序()](http://en.cppreference.com/w/cpp/algorithm/sort),通常你“会在这头是在 – ChiefTwoPencils 2013-02-18 23:25:25

回答

8

你觉得老师忘了在#include行?

是的。

他一定忘了:

#include <algorithm> 

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

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

#include <functional> 

这就是标准库头的函子如std::greater<>,你做在这里使用。

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

+0

需要定义的顶部看到'#包括''为更大'以及... – ildjarn 2013-02-19 00:30:57

+0

@ildjarn:正确的,良好的渔获物。我现在无法编辑我的答案(在手机上输入),如果您愿意,可以随时添加。 – 2013-02-19 00:40:04

+0

Re:'display()'不返回一个值:马虎,但在这里无害。 :-(它的返回类型应该是'void' – 2013-02-19 12:24:19

5

是的,你需要为#include <algorithm>std::sortstd::for_each,这是最有可能你想,当你说sortfor_each叫什么。该算法的作用是按增加顺序对数组a进行排序并将元素输出到stdout。