Vector sorting base on 2 variables in the object

Hello all, I have a sorting function from lowest to highest, highest to lowest, and sort by the type then highest to lowest for each of its type.

ShapeTwoD is my object now, which is also a parent class.
I have 3 sub classes for polymorphism which i store the sub class objects into the vector.

Below are the codes to sort by area. In the object itself, there are also shape types being stored as well, which are "WS" and "NS". I want to sort it base on "WS" first, followed by "NS". After which, it will then sort highest to lowest in "WS", followed by highest to lowest in "NS".

I need some advice and ideas on how to do this sort. Thanks in advance

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
bool compareAscend(const ShapeTwoD* a, const ShapeTwoD* b)
{ 
	return b->getArea() > a->getArea();       
}

bool compareDescend(const ShapeTwoD* a, const ShapeTwoD* b)
{ 
	return a->getArea() > b->getArea();		
}

void Sort(vector<ShapeTwoD*>& Vector)
{
	string choice;

	cout << "\n\na)\tSort by area (ascending)" << endl;
	cout << "b)\tSort by area (descending)" << endl;
	cout << "c)\tSort by special type and area" << endl;

	cout << "\tPlease select sort option (‘q’ to go main menu): ";
	cin >> choice;
	transform(choice.begin(), choice.end(), choice.begin(), ::tolower);

	if (choice == "a")
	{
		sort(Vector.begin(), Vector.end(), compareAscend);
	}
	else if (choice == "b")
	{
		sort(Vector.begin(), Vector.end(), compareDescend);
        }
}

Last edited on
b u m p
First sort by area, then sort by shape.

Example of a data set:

A8 B3 B7 A5 A2 B1

Sorted by numbers:

B1 A2 B3 A5 B7 A8

Then sort by letters:

A2 A5 A8 B1 B3 B7
Hi there- you can create a custom sort object with an overloaded operator that will allow you to sort by any parameters you would like. You just provide a comparison function.

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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct container{
    int first, second;
};

struct comparer{
    inline bool operator()(const container& one, const container& two){
        return one.first < two.first || (one.first==two.first && one.second < two.second);
    }
};

int main(){

    vector<container> vec(220);

    for(int a = 0; a < vec.size(); a++){
        vec[a].first = a % 22;
        vec[a].second = a % 31;
    }

    sort(vec.begin(),vec.end(),comparer());

    for(int a = 0; a < vec.size(); a++){
        cout << "\n" << vec[a].first;
        cout << "," << vec[a].second;
    }

}


Something like that would work. You can figure out a way to use additional parameters (like ascending and descending) on your own I'm sure.

(edit, you can also use your functions, just look at my snippet's return function to figure out your double sort)
Last edited on
Topic archived. No new replies allowed.