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

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

问题描述

我使用C ++中的 sort()函数对Game类型的对象向量进行排序,这是我自己定义的。为此,我手动编写一个函数代替运算符< ,它将作为第三个参数传递给 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) / code>,如果 s1 会出现在字典中的 s2 之前,例如:

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.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();

您的自定义游戏类可以将其小于比较运算符实现为:

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天全站免登陆