How to sort a vector of structs based on a vector<string> within the vector to be sorted?
c++, sorting, struct, vector
Solution
Provide a suitable comparison binary function and pass it on to `std::sort`. For example
bool cmp(const sentence& lhs, const sentence & rhs)
{
return lhs.words[0] < rhs.words[0];
}
then
std::sort(allSentences.begin(), allSentences.end(), cmp);
Alternatively, in C++11 you can use a lambda anonymous function
std::sort(allSentences.begin(), allSentences.end(),
[](const sentence& lhs, const sentence & rhs) {
return lhs.words[0] < rhs.words[0];}
);
Problem
What is the best way to alphabetically sort a vector of structures based on the first word in every vector of all the structures in the vector of structures? ``` struct sentence{ vector<string> words; }; vector<sentence> allSentences; ``` In other words, how to sort allSentences based on words[0]? EDIT: I used the following solution: ``` bool cmp(const sentence& lhs, const sentence & rhs) { return lhs.words[0] < rhs.words[0]; } std::sort(allSentences.begin(), allSentences.end(), cmp); ```