Sorting a vector

The following is my vector. I have 118 of them, one for each element in the periodic table. How could I sort them as needed, if I want to display them alphabetically, or by the atomic number, depending on which the user chooses? Right now, I display the elements alphabetically in a list onscreen, but would also like to be able to display them according the the atomic numbers, is so desired.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct Element
{
	int Atomic_Number;
	int x;// To display onscreen, using gotoXY(x,y);
	int y;
	string Symbol;
	string Name;
	double Atomic_Weight;
	float Melting_Point;
	float Boiling_Point;
	double Density;
	int Discovery_Year;
	double Ionization_Energy;
	int Element_Type;
	int Element_State;
};


Thanks for any help
You can use std::sort and use different comparison functions for each way of sorting.
1
2
3
4
5
6
7
8
9
bool cmpElementsAlphabetically(const Element& e1, const Element& e2)
{
	return e1.Name < e2.Name;
}

bool cmpElementsAtomicNumber(const Element& e1, const Element& e2)
{
	return e1.Atomic_Number < e2.Atomic_Number;
}


1
2
3
4
5
// sort alphabetically
std::sort(elem_vec.begin(), elem_vec.end(), cmpElementsAlphabetically);

// sort by atomic number
std::sort(elem_vec.begin(), elem_vec.end(), cmpElementsAtomicNumber);
Last edited on
@mutexe

Thanks for the link. I'll save the page so I can get back to it to refresh my memory, if/when I do another program with vectors, and need to manipulate them.

@Peter87

Thanks for the help. I didn't think it would be that easy to sort the vector in those ways. After adding in #include <algorithm> , it worked like a charm. Thanks again..
Last edited on
Topic archived. No new replies allowed.