Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ custom sorting a vector

Not going to go too deep into what I am doing because it is homework and I don't need it done for me but, I do need some help. I need to be able to specify what part of a vector<vector<string>> gets sorted first and under what parameters.

Currently what I am doing works perfectly by calling

sort ( v.begin(), v.end() );

If you write out my vectors they will look something like:

5 2 4 6 12 2 5

22 51 2 5 72 1

And I might need to sort it in descending order by the 2nd column and if the 2nd column is the same I would then sort by the next specified column.

called like ./sort 2,4

would sort by second column and then 4th.

I looked around and apart from writing my own sorting algorithm for this I don't know how I would customize the sort.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

std::sort() has a second form that takes a compare functor as a third parameter. This lets you control the ordering of the sort without having to write the sort algorithm yourself.

The function you provide is given two objects, and must return true if the first object should be ordered before the second ("less than") and false otherwise.

E.g.:

std::sort(v.begin(), v.end(), [](const vector<string>& v1, const vector<string>& v2) {
    // return true if v1 < v2, false otherwise
});

(Of course, it's up to you to work out the logic you need to get the sort ordered how you want it.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...