c++ how to determine whether one word is before another in the alphabet(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),如果 s1 在 s2 之前,它将返回 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 ++如何确定字母表中一个单词是否在另一个单词之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c ++如何确定字母表中一个单词是否在另一个单词之前
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
