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

Categories

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

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

1 Answer

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...