C++ 如何基于向量对结构向量进行排序<;字符串>;在要排序的向量内?
根据结构向量中所有结构的每个向量中的第一个单词,按字母顺序对结构向量排序的最佳方法是什么C++ 如何基于向量对结构向量进行排序<;字符串>;在要排序的向量内?,c++,sorting,vector,struct,C++,Sorting,Vector,Struct,根据结构向量中所有结构的每个向量中的第一个单词,按字母顺序对结构向量排序的最佳方法是什么 struct sentence{ vector<string> words; }; vector<sentence> allSentences; 结构句{ 向量词; }; 向量所有句子; 换句话说,如何根据单词[0]对所有句子进行排序 编辑:我使用了以下解决方案: bool cmp(const sentence& lhs, const sentence &am
struct sentence{
vector<string> words;
};
vector<sentence> allSentences;
结构句{
向量词;
};
向量所有句子;
换句话说,如何根据单词[0]对所有句子进行排序
编辑:我使用了以下解决方案:
bool cmp(const sentence& lhs, const sentence & rhs)
{
return lhs.words[0] < rhs.words[0];
}
std::sort(allSentences.begin(), allSentences.end(), cmp);
// Sort lexicographical by first word
std::sort(allSentences.begin(), allSentences.end(),
[](const sentence& a, const sentence& b) {
a.words[0] < b.words[0];
});
bool-cmp(常量句和左侧、常量句和右侧)
{
返回lhs.words[0]
您需要一些比较函数,可以传递到std::sort
:
bool compare(const sentence& a, const sentence& b)
{
return a.words[0] < b.words[0];
}
当然,使用这种比较意味着像
{“hello”,“world”}
和{“hello”,“friend”}
这样的句子将进行相等的比较。但这正是您所要求的。提供一个合适的比较二进制函数,并将其传递给std::sort
。比如说
bool cmp(const sentence& lhs, const sentence & rhs)
{
return lhs.words[0] < rhs.words[0];
}
或者,在C++11中,可以使用lambda匿名函数
std::sort(allSentences.begin(), allSentences.end(),
[](const sentence& lhs, const sentence & rhs) {
return lhs.words[0] < rhs.words[0];}
);
std::sort(所有句子.begin(),所有句子.end(),
[](恒句和左、恒句和右){
返回lhs.words[0] > p>通常,您需要考虑的三种不同类型的比较实现方案。
对对象进行比较,使始终有意义。它独立于要比较对象的场景。然后:实现运算符,为您的伟大答案提供答案。也许有人可以解释为什么这不起作用:返回lhs.wordCombinated[0]。比较(rhs.wordCombinated[0]);
std::sort(allSentences.begin(), allSentences.end(),
[](const sentence& lhs, const sentence & rhs) {
return lhs.words[0] < rhs.words[0];}
);
struct sentence{
vector<string> words;
bool operator<(const sentence &other) const {
return this->words[0] < other.words[0];
}
};
std::sort(allSentences.begin(), allSentences.end());
// Sort lexicographical by first word
std::sort(allSentences.begin(), allSentences.end(),
[](const sentence& a, const sentence& b) {
a.words[0] < b.words[0];
});
// 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);