简体   繁体   中英

What does the following code produce?

I don't know if this is a trick question or what, but when I try to run this piece of code, I get a few errors. Do you think the teacher forgot to put in an #include line?

#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

Thanks

Do you think the teacher forgot to put in an #include line?

Yes.

He definitely forgot to:

#include <algorithm>

That's the Standard Library header for algorithms such as std::sort and std::for_each , which is precisely what your compiler complains about.

Incidentally, despite the fact that your compiler didn't complain about this (yet), he also forgot to:

#include <functional>

That's the Standard Library header for functors such as std::greater<> , which you make use of here.

Besides, your (teacher's?) display() function should have void as its return type, as it currently returns no value.

Yes, you need to #include <algorithm> for std::sort and std::for_each , which is most likely what you are trying to call when you say sort and for_each . The effect of the algorithm is to sort array a in increasing order and print the elements to stdout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM