Sorting with Vector
#include <iostream> #include <vector> #include <algorithm> using namespace std; /* Sort comparison to get an descending sort. */ bool descend(int x, int y) { return y < x; } /* Comparison where odds come first and ascend, evens come last and descend. */ bool evenodd(int x, int y) { if(x&1) { // First number is odd. if(y&1) // So is the second. Just use their normal order. return x < y; else // First odd, second even, so first is always first. return true; } else { // First number even. if(y&1) // Second odd. Second should go first. return false; else // Both even. Use reverse order to get descending. return y < x; } } /* * Print the vector. NOTE: vector passed by constant reference. */ void print(const vector<int> &vec) { vector<int>::const_iterator i; for(i = vec.begin(); i != vec.end(); ++i) { cout << *i << " "; } cout << endl; } /* * Simple STL vector list demo. */ int main() { vector<int> vec; // Read some integers into the vector. int in; cout << "Please enter some integers for testing." << endl; while(cin >> in) { vec.push_back(in); } cout << "----------------------------------------" << "----------------------------------------" << endl; // Print them. print(vec); cout << endl; // Sort them ascending, and print. sort(vec.begin(), vec.end()); print(vec); // Sort them descending, and print. sort(vec.begin(), vec.end(), descend); print(vec); // Sort them so that odd ones come last, and print. sort(vec.begin(), vec.end(), evenodd); print(vec); }

Have a look at the print method. It accepts the vector by reference. It is very common to pass collections by reference, because regular parameter passing makes copies. Copying an integer parameter is no big deal, but copying a collection is rather expensive when not needed. But when a function receives a parameter by reference, it can change it. The print function uses the const modifier, which is a promise that it won't change the collection. This promise is enforced by the compiler: Any attempt to change the parameter vector inside print will produce a compiler error.

This again uses the library sort that we used with arrays. It takes an iterator to the first, and one past the last data to sort. In this example, we perform several sorts by sending a comparison function as the (optional) third parameter. C++ allows functions to be sent as parameters.

The first sort does not have a comparison parameter and performs the default ascending sort. The second and third receive the name of a function defined earlier in the file. Note that these comparisons take two parameters to compare, but do not not return their result as a signed integer as Java's compareTo. They simply tell if the first is less than the second.

The second sort sorts descending by comparing is arguments backwards. The third creates a very strange order where odd numbers come first and ascend, and even numbers come last and descend.