Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

c++ - Sorting a list of a custom type

I want to have a stl list of objects where each object contains two int's. Afterwards I want to sort the list with stl::sort after the value of the first int. How do I tell the sort function that it's supposed to sort after the first int?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can specify a custom sort predicate. In C++11 this is best done with a lambda:

typedef std::pair<int, int> ipair;
std::list<ipair> thelist;

thelist.sort([](const ipair & a, const ipair & b) { return a.first < b.first; });

In older versions of C++ you have to write an appropriate function:

bool compFirst(const ipair & a, const ipair & b) { return a.first < b.first; }

thelist.sort(compFirst);

(Instead if ipair you can of course have your own data structure; just modify the comparison function accordingly to access the relevant data member.)

Finally, if this makes sense, you can also equip your custom class with an operator<. That allows you to use the class freely in any ordered context, but be sure to understand the consequences of that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...