## Custom sort in C++ adding attributes

Hi,

Asked By
260 points
N/A
Posted on - 05/13/2011

Hi,

I have a vector of objects defined as follows:

class items

{

public:

string name;

int cost;

int weight;

};

I need to sort it first on the basis of cost. If cost are equal on the basis of weight, if they are equal too. I need them in the alphabetic order.

I am doing some brute force loop, to sort them based on cost.

void Sorter(vector<items> &v)

{

bool done=false;

while(!done)

{

done=true;

for(int i=v.size()-1;i>0;–i)

{

if(v[i-1].cost>v[i].cost){swap(v[i-1],v[i]);done=false;}

}

}

}

But how do I add other attributes? They are just getting messy.

If you are learning the ways of sort, then yes it would be complicated. Just add every condition in the swap instead of just

If(v[i-1].cost>v[i].cost)

And if you are just doing this as a part of something big, then you should use the sort() function in algorithm. It is much faster and smoother.

Bill,

Bubble sort is not as quick as quick sort.

You should try that and yes, as software synthesis said, there is simply no need to re-invent the wheel. There is a sort function in algorithm. All you need to do is define in a comparator function.

To know how to use a comparator function, you can read this.

Thanks very much.

I know there is a function sort() in algorithm but I don't know how to use it with a comparator function.

How do I declare a comparator function?

Bill,

It is very easy. Just like any other ordinary function. Its return type is blue and takes 2 parameters a and b.

Suppose a and b are 2 consecutive elements of the vector.

If a and b is in proper placements i.e a<b (for ascending) then return true, else return false.

But I have 3 properties to be considered;

- String name;
- Int cost;
- Int weight;

Do I need 3 comparator functions? or 1 to do all of them ? Then how many parameter would there be? 6?

Best Answer

Best Answer

You don't need to pass all the properties. Just pass the two objects and access their properties, from within the function. Here is a simple comparator function to help you out

bool comparator(items a,items b)

{

if(a.cost>b.cost)

return false;

if(a.cost<b.cost)

return true;

else if(a.weight>b.weight)

return false;

else if (a.weight<b.weight)

return true;

else if(a.name>b.name)

return false;

else

return true;

}

Try this and I think you shall get it soon.

Thanks a lot Software Synthesis. I got that finally. It's really amazing.