0

It seems like I can define an operator for a struct and use std::sort for the sorting - the issue I'm seeing with this is that it seems like I can only define one sorting method. I'd like to define two others based on other fields. Is it possible to define more?

Otherwise, the only other thing I can think of is to move the structures into a vector and sort the vector using functions defined for each sort. I'm fine with handling it that way but I'm wondering if there is a more ideal way of handling sorting of structures in a queue by its fields.

For example, with this struct...

struct job
{
    int id;
    int start;
    int end;

    bool operator<(Process const &other) { return start < other.start; }
};

queue<jobSet>

I know I can set up a bool to sort by start...

sort(begin(jobSet), end(jobSet));

But I'm not sure how to set up another sort that works with the end field

2
  • It's not clear what you're trying to accomplish. My guess is you want to sort objects of a certain type differently depending on the context? You can pass your own comparator to std::sort, so that's easily achievable. You should clarify your question if this isn't what you want. Commented Mar 2, 2016 at 5:11
  • Ok I've added sample code Commented Mar 2, 2016 at 11:50

1 Answer 1

1

U can define your custom comparer for sorting, i.e.

struct compareStart{
    bool operator<(Job const& a, Job const& b) { return a.start < b.start; }
}

struct compareEnd{
    bool operator<(Job const& a, Job const& b) { return a.end < b.end; }
}

Then you can use it like

sort(begin(jobSet), end(jobSet), compareStart());
sort(begin(jobSet), end(jobSet), compareEnd());

Or if you have c++11 use lambdas:

sort(begin(jobSet), end(jobSet), [](Job const& a, Job const& b) { return a.end < b.end; });

You do not have to use the comparisson oprator of the job object

Sign up to request clarification or add additional context in comments.

1 Comment

Ah ok - I thought I had to work with the comparison operator. This is helpful..thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.