问题
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.
回答1:
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.)
来源:https://stackoverflow.com/questions/31175160/c-custom-sorting-a-vector