How to sort vector(s) Z to A?

Hello, I'm trying to figure out how to sort a vector from Z to A. Or even if I was dealing with numbers how to go from Greatest to Least in integer values?
I figured out A-Z in this code here. I also know how to sort numbers from Least to Greatest. I don't understand sorting the other way around. Any help would be appreciated! Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm> //used for the sort function
#include <string>
using namespace std;

int main ()
{
	vector <string> FirstNames;
	FirstNames.push_back("Ray");
	FirstNames.push_back("Jecka");
	FirstNames.push_back("Nathan");
	FirstNames.push_back("Alyssa");
	FirstNames.push_back("Monica");

	string lastnames[5] = {"Weiserman", "Alan", "Bohnson", "Landers", "Hart"};
	vector <string> LastNames (lastnames, lastnames+5);

	sort (FirstNames.begin(), FirstNames.end());
	sort (LastNames.begin(), LastNames.end());


	cout << "These are the students in alphabetical order by first name. (A-Z)\n" << endl;

	for (int x = 0; x < 5; x++)
	{
		cout << FirstNames[x] << " " << LastNames[x] << endl;
	}

	system("pause");
	return 0;
}
If you consult documentation for the std::sort function, you'll see that there are several versions of the function and one of them takes, as it's third argument, a comparison function/object.

std::sort(FirstNames.begin(), FirstNames.end());
is equivalent to
std::sort(FirstNames.begin(), FirstNames.end(), std::less<std::string>{});

Any guess as to what
std::sort(FirstNames.begin(), FirstNames.end(), std::greater<std::string>{});
will do?

Header file required for std::less/std::greater is <functional>
closed account (E0p9LyTq)
You could use std::sort to sort in ascending order, and then std::reverse_copy to invert the sorted order, both in <algorithm>.

Requires a temp vector, but is quick and dirty easy.
std::sort( FirstNames.rbegin(), FirstNames.rend() ) ; // note: reverse_iterators
closed account (E0p9LyTq)
JLBorges wrote:
// note: reverse_iterators

D'OH!

Wouldn't std::reverse work as well?
> Wouldn't std::reverse work as well?

Yes; first sort in ascending order and then reverse the sequence.
closed account (E0p9LyTq)
JLBorges wrote:
Yes; first sort in ascending order and then reverse the sequence.

Still a two step solution, using reverse iterators takes one step.

More to learn and unlearn.
Topic archived. No new replies allowed.