138 Introduction to C++ Programming and Graphics
These two statements can be replaced by the single statement:
sort(v, v+N)
which confirms that the vectorvis passed to the function as a pointer.
The following code contained in the filesorting.ccuses thesortfunction
of the STL to sort and then print a list:
#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
int main()
{
const int N=7;
float v[N]={10.0, -9.4, 3.4, -3.4 -10.8, 199.0, -3.56};
sort(v, v+N);
cout<< setiosflags(ios::fixed | ios::showpoint);
for(int i=0;i<=N-1;i++)
{
cout << setw(3) << i << " " << setw(6) << setprecision(2)
<< v[i] << endl;
}
return 0;
}
Note that we have included the header filealgorithmof the STL. Running the
code prints on the screen:
0 -14.20
1 -9.40
2 -3.56
3 0.00
4 3.40
5 10.00
6 199.00
If we only want to sort a subset of the list, we can state, for example,
float * pnt = &v[3];
sort(pnt, pnt+2);