Reputation: 45
I am new to C++ and I would like to know how to use the sort function. This is my code and it's not working for some reasons:
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
ifstream in("date.in");
ofstream out("date.out");
int v[5]= {2, 3 ,1, 0, 5};
sort(begin(v), end(v));
for(int j=0; j<5; j++){
out<<v[j]<<" ";
}
return 0;
}
The error code I get is:
error: 'begin' was not declared in this scope
Upvotes: 1
Views: 15134
Reputation: 6404
There are two solutions.
std::sort takes an iterator to the start of the sequence, and one to one past the end of the sequence. This is the convention for stl algorithms which work on collections.
So
std::vector v = {2, 3, 0, 1, 5};
sort(v.begin(), v.end());
or
int v[5] = {2, 3, 0, 1, 5};
sort(v, v + 5);
plain pointers are iterators as well as stl::iterator types declared in the stl headers.
Upvotes: 2
Reputation: 9908
You need to include the #include <iterator>
. Because std::begin
defined under iterator.
Or else change the type from array
to vector
and your code will work.
Upvotes: 4
Reputation: 1247
replace sort(begin(v), end(v));
with sort(v, v + 5));
v
is an array not a vector. For vectors use sort(v.begin(), v.end());
Upvotes: 0