Sort Descending and Ascending

Hi ;
Please help on the code below. I want sort the names entered by the user in Ascending and descending order but the ascending order is not working and I have comment that one out.

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
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

void getNameVector(vector<string> &vect){
	string name;
	for(int i=0; i<5; i++){
	
		cout<<"Enter your name: ";
		getline(cin,name);
		vect.push_back(name);
	}
}

void displayNameVector(vector<string> vect){
	for(int i=0;i<vect.size();i++){
	cout<<vect[i]<<endl;
}
}

int main(){
	
	
	vector<string> names;
	getNameVector(names);
	
	cout<<"List of names entered"<<endl;
	displayNameVector(names);
	
	cout<<endl;
	cout<<"Descending order of the names: "<<endl;
	//sorting in descending order	
	sort(names.begin(),names.end());
	displayNameVector(names);
	
		cout<<endl;
	cout<<"Ascending order of the names: "<<endl;
	//sorting in ascending order	
	sort(names.end(),names.begin());
	displayNameVector(names);
	
		
	return 0;
}
sort(names.end(),names.begin());
Never ever do that. End iterator should be after begin iterator, that means if you will increment begin iterator it in the end will become equal to end and all its value will be within single container. Otherwise you get undefined behavior.

To sort in another order you can simply pass another comparsion function:
1
2
3
#include <functional>
//...
std::sort(names.begin(),names.end(), std::greater<std::string>());
Thanks for your time but I hardly understand what you mean.
std::sort takes three parameters. First is iterator to the beginning of range. Second is the one-past-the-end iterator. Third optional one is the function which will be used for comparsion. By default operator < is used.

You can define function yourself of use templated one provided by standard library. Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*1)
 *Using user defined function
 */
bool larger(const std::string& lhs, const std::string& rhs)
{
    return lhs > rhs;
}
//...
std:sort(names.begin(),names.end(), larger);

/*2)
 *Using std::greater defined in <functional>
 */
#include <functional>
//...
std:sort(names.begin(),names.end(), std::greater<std::string>());

/*3)
 *Using lambdas
 */
std:sort(names.begin(),names.end(), [](const std::string& lhs, const std::string& rhs){return lhs > rhs;});
I would like to add one more option, you can also use reverse iterators
sort(names.rbegin(), names.rend());
Topic archived. No new replies allowed.