Vector sorting with different objects in it

Hello all, I am trying to come out with a sort function, previously, with some help, manage to do a sort that sorts base on a variable that is stored into an object vector.

PointTwoD is my object.

1
2
3
4
5
6
7
8
9
10
11
bool compare(const PointTwoD& a, const PointTwoD& b)
{ 
	return a.getcivIndex() > b.getcivIndex();
	//sort from high to low	
}

//to do the sort, i will just have to call it in my function
void Sort(vector<PointTwoD>& Vector)
{
         sort(Vector.begin(), Vector.end(), compare);
}


Base on this, i tried to recreate it.

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.

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

bool compareDescend(ShapeTwoD& a, ShapeTwoD& b)
{ 
	return a.getArea() > b.getArea();		
}
//if i only compile this, the compiler is fine with this

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);
                //these lines are giving the error
	}
	else if (choice == "b")
	{
		sort(Vector.begin(), Vector.end(), compareDescend);
                //these lines are giving the error
        }
}


But when i try to compile, the compiler will give me A LOAD of errors, which i don't understand.
Last edited on
You are trying to pass a pointer to ShapeTwoD when compare function is expecting an instance of ShapeTwoD. Either change your Vector to vector<ShapeTwoD> or change your compare function to take pointers to ShapeTwoD instead of references.
The vector has objects of some type and the sort passes those objects to the compare.

The same issue (without vector and sort) is seen here:
1
2
3
4
5
6
7
8
9
10
11
bool compareAscend( const ShapeTwoD &, const ShapeTwoD & );

int main() {
  ShapeTwoD foo;
  ShapeTwoD bar;
  compareAscend( foo, bar ); // Ok

  ShapeTwoD * pfoo;
  ShapeTwoD * pbar;
  compareAscend( pfoo, pbar ); // Error
}


How about:
bool compareAscend( const ShapeTwoD *, const ShapeTwoD * );
Oh, understood, have change and it works now, thanks.
Topic archived. No new replies allowed.