如何根据要排序的向量中的向量对结构<string>向量进行排序?
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]对所有句子进行排序?
EDIT:我使用了以下解决方案:
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,请使用第三种解决方案:
-
一组不同的、可重用的比较方法,可能是一个参数化的比较函数。例如:通过第一个单词比较,通过长度比较,通过其他东西比较……在这种情况下,将比较函数实现为独立函数并使用函数指针,或者将它们实现为函子(可以参数化)。此外,在这种情况下,存储在变量中的lambdas可以完成这项工作。
此方法的优点是命名比较方法,赋予它们意义。如果您对同一个对象使用不同的比较,但是重用它们,这是一个巨大的优势:
// 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);
- 将结构向量排序为子组
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 如何在对向量排序后更改索引值?c++
- C++向量排序给出0作为输出
- 将许多向量排序在一起
- 根据一个向量对多个向量排序
- 编译错误向量排序和联合
- C++我自己的函数进行向量排序
- 将字符串的向量排序为日期"yyyymmdd"
- C++ 通过使用旧向量进行预排序来改进向量排序
- C 向量排序 .h .cpp中的单独文件
- 向量排序-c++
- 将向量排序到一个无序映射c++11中
- 向量的向量排序
- c++向量排序方法编译失败,返回预期表达式
- 如何对bitset向量排序
- 向量排序的基础上只有先
- 我如何以相同的方式对两个向量排序,而条件只使用其中一个向量
- 列表排序和结构体向量排序之间的性能差距.c++
- 如何基于第二个字符串对字符串向量的向量排序