c ++如何确定字母表中一个单词是否在另一个单词之前 [英] c++ how to determine whether one word is before another in the alphabet

查看:29
本文介绍了c ++如何确定字母表中一个单词是否在另一个单词之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C++ 中的 sort() 函数对我自己定义的游戏"类型的对象向量进行排序.为此,我手动编写了一个函数来代替 operator<,并将其作为第三个参数传递给 sort() 函数.首先,我根据分数进行比较.然后,如果分数相同,我会根据团队名称进行比较.

I'm using the sort() function in C++ to sort a vector of objects of type 'Game', which I defined myself. To do this, I am manually writing a function that will act in place of the operator<, and which will be passed as the third parameter to the sort() function. First, I compare based on scores. Then, if scores are tied, I compare based on team name.

我需要的是一个函数 alphabetical(string s1, string s2),如果 s1s2 之前,它将返回 true词典.例如:

What I need is a function alphabetical(string s1, string s2), that will return true if s1 would come before s2 in the dictionary. For example:

alphabetical("aardvark", "apple"); //true
alphabetical("balloon", "zebra"); //true
alphabetical("zebra", "apple"); //false

如果字符串相同,我也希望它返回 false.图书馆里有我可以使用的东西吗?或者,我将如何编写函数?我希望我能清楚地表达出来.

I also want it to return false if the strings are identical. Is there something in a library that I could use? Or, how would I write the function? I hope I'm coming across clearly.

推荐答案

std::string 自己实现了一个按字典顺序排列的小于比较运算符,这意味着 stringA <stringB 通常应该做你想做的事.如果你创建一个 std::list<std::string>words,按字母排序就像 words.sort();

std::string implements a lexicographical less-than comparison operator itself, meaning that stringA < stringB should usually do what you want. If you create a std::list<std::string> words, sorting alphabetically will be as simple as words.sort();

您的自定义 Game 类可以将其小于比较运算符简单地实现为:

Your custom Game class could have its less-than comparison operator implemented simply as:

return (score < rhs.score) || (score == rhs.score && team < rhs.team)

值得注意的是,字典排序并不总是人类所期望的.Jeff Atwood 在 这篇文章.他的帖子还提供了资源,如果您需要这种排序,您可以从中找到算法.

It is worth noting that lexicographical sorting will not always be what a human would expect. Jeff Atwood goes into a discussion of so-called "natural sort order" versus lexicographical sort order in this post. His post also provides resources from which you will be able to find algorithms if such sorting is necessary to you.

这篇关于c ++如何确定字母表中一个单词是否在另一个单词之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆