[英]How to sort a vector of structs based on a vector<string> within the vector to be sorted?
基於結構向量中所有結構的每個向量中的第一個單詞按字母順序對結構向量進行排序的最佳方法是什么?
struct sentence{
vector<string> words;
};
vector<sentence> allSentences;
換句話說,如何基於單詞[0]對allSentence進行排序?
編輯:我使用以下解決方案:
bool cmp(const sentence& lhs, const sentence & rhs)
{
return lhs.words[0] < rhs.words[0];
}
std::sort(allSentences.begin(), allSentences.end(), cmp);
提供合適的比較二進制函數並將其傳遞給std::sort
。 例如
bool cmp(const sentence& lhs, const sentence & rhs)
{
return lhs.words[0] < rhs.words[0];
}
然后
std::sort(allSentences.begin(), allSentences.end(), cmp);
或者,在C ++ 11中,您可以使用lambda匿名函數
std::sort(allSentences.begin(), allSentences.end(),
[](const sentence& lhs, const sentence & rhs) {
return lhs.words[0] < rhs.words[0];}
);
你需要一些比較函數,你可以傳遞給std::sort
:
bool compare(const sentence& a, const sentence& b)
{
return a.words[0] < b.words[0];
}
如您所見,它需要兩個sentences
,如果第一個sentence
的第一個單詞“小於”第二個sentence
的第一個單詞,則返回true。
然后你可以很容易地對allSentences
進行排序:
std::sort(allSentences.begin(), allSentences.end(), compare);
當然,使用這種比較意味着像{"hello", "world"}
和{"hello", "friend"}
類的句子將相等。 但這就是你所要求的。
通常,您應該考慮三種不同類型的場景用於比較實施。
比較你的對象總是有意義的。 它獨立於您想要比較對象的場景。 然后:為您的班級實施operator<
。 只要比較兩個對象(使用<
,標准算法所做的),就會使用此運算符。 (對於單個場景,您仍然可以使用下面的其他方法“覆蓋”此行為)。
為此,使用以下函數擴展您的類:
struct sentence{ vector<string> words; bool operator<(const sentence &other) const { return this->words[0] < other.words[0]; } };
然后,只需在您的句子向量上調用標准排序算法,而無需其他參數:
std::sort(allSentences.begin(), allSentences.end());
然而,您的情況聽起來並不像這是最好的方法,因為通過第一個字比較是你不希望有永遠 ,也許只有在一種情況下的東西。
對象的比較, 只使用一次 。 在C ++ 11中,您有lambda函數(匿名,字面內聯函數),它們可以直接傳遞給將在其中使用的算法函數,如此場景中的std::sort
。 這是我最喜歡的解決方案:
// Sort lexicographical by first word std::sort(allSentences.begin(), allSentences.end(), [](const sentence& a, const sentence& b) { a.words[0] < b.words[0]; });
在C ++ 03中,你沒有lambdas,請使用第3個解決方案:
一組不同的,可重復使用的比較方法,可能是參數化比較函數。 示例是:通過第一個單詞比較,按長度進行比較,通過其他方式進行比較...在這種情況下,將比較函數實現為獨立函數並使用函數指針,或將它們實現為函子(可以參數化)。 此外,存儲在變量中的lambda在這種情況下可以完成工作。
這種方法的優點是命名比較方法,賦予它們意義 。 如果對同一個對象使用不同的比較,但重用它們,這是一個巨大的優勢:
// Lexicographical comparison by the first word only bool compareLexByFirstWord(const sentence& a, const sentence& b) { return a.words[0] < b.words[0]; } // Lexicographical comparison by all words bool compareLex(const sentence& a, const sentence& b) { return a.words < b.words; } // Decide which behavior to use when actually using the comparison: std::sort(sentence.begin(), sentence.end(), compareLexByFirstWord); std::sort(sentence.begin(), sentence.end(), compareLex);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.