下面的代码产生什么
What does the following code produce?
我不知道这是不是一个技巧问题,但当我试图运行这段代码时,我会遇到一些错误。你认为老师忘了写#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::sort
和std::for_each
等算法的标准库头,这正是编译器所抱怨的。
顺便说一句,尽管你的编译器还没有抱怨这一点,但他也忘记了:
#include <functional>
这是函数(如std::greater<>
)的标准库头,您可以在这里使用它。
此外,您的(教师的?)display()
函数的返回类型应该是void
,因为它目前没有返回值。
是的,std::sort
和std::for_each
需要#include <algorithm>
,这很可能是您在说sort
和for_each
时想要调用的。该算法的效果是按递增顺序对数组a
进行排序,并将元素打印到stdout。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 0-1背包代码中的错误.我的代码中有什么错误
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 这行代码在C++类中意味着什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 我可以做些什么来消除或最小化这种将提供相同功能和行为的代码重复
- 以下 C++ 代码用于 -> "#define idiv(a, b) (((a) + (b) / 2) / (b))" 是什么?
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 此代码中的操作流程是什么?C/C++.
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 此代码验证公式是什么意思?
- 这是什么代码?为什么它有效?C++
- 当您希望在Arduino Uno编程中同时执行不同函数时,使用什么代码/语句
- 这是什么代码?C或C
- 在 c++ 中应该使用什么代码而不是 getche
- 什么代码更适合用于运算符重载
- 什么代码可以使这个循环工作