对向量进行排序按字母顺序
我有一个 std::vector
不在下面的结构中:
struct Word
{
std::string word;
int line_number;
};
我已经从文件中读取了单词,并将其推送到我的向量中,该向量存储了上面字符串中的单词以及该单词出现的行号。现在我需要按字母顺序对单词进行排序,并尝试执行以下操作:
std::sort(data.begin(), data.end());
但是,当我尝试编译以下内容时,我得到了一长串疯狂的错误。我相信这是由于排序算法尝试将向量.begin() 与向量.end() 进行比较,但它不知道如何将结构词评估为另一个结构词。
然而我也没有。我对如何比较向量中包含的字符串和结构感到困惑。
I have a std::vector<Word> data
that is off of the struct below:
struct Word
{
std::string word;
int line_number;
};
I have read in words from a file and pushed it in to my vector storing the words in the string above along with the line number that the word appears on. Now I need to sort the words alphabetically and I attempt the following:
std::sort(data.begin(), data.end());
However when I try to compile the following I get a crazy long list of errors. I believe this is due to the sort algorithm trying to compare the vector.begin() to vector.end() but it doesn't know how to evaluate the struct word to another struct word.
However neither do I. I am stumped on how to compare the string contained with the structs in the vector.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下,您应该编写一个比较两个
Word
结构的函数,并将该函数传递给std::sort
。如果您想编写一个通用比较器来基于属性比较对象,则可以在这个问题中找到解决方案。
更新 由于我们已经使用 C++11 和 C++14 一段时间了,我正在使用 lambda 添加一个解决方案,因为这可能是现在更好的做法:
In this scenario you should write a function that compares two
Word
structs and pass that function tostd::sort
.In this question you can find solution if you want to write a generic comparator for comparing objects based on an attribute.
Update Since we've had C++11 and C++14 for a while now, I'm adding a solution using a lambda, because that is probably the better practice now:
您应该将
operator<
实现到您的struct Word
you should implement
operator<
to yourstruct Word
您还可以使用以排序方式存储其项目的容器,而不是事后对向量进行排序。
Instead of sorting the vector afterward, you can also use a container which stores its items in a sorted manner.
如果您的编译器支持 lamda 表达式,您只需添加一个作为比较函数即可。
If your compiler supports lamda expressions you could just add one as the compare function.