[英]How to lexographically compare two vectors of strings?
I am doing a C++ exercise where I have to implement a class representing a weak version of a vector that holds a string. 我正在执行C ++练习,其中我必须实现一个类,该类表示持有字符串的向量的弱版本。 One of the requirements is to overload the < and > operator following the rules of lexographical comparison.
要求之一是按照字典比较规则重载<和>运算符。
I've been reading up on the algorithm but I don't understand it at all or how to implement it. 我一直在阅读算法,但我完全不了解它或如何实现它。 What makes a vector < than the other?
什么使向量<小于另一个? What do I compare from the strings?
我从字符串中比较什么? The private variables are string *array, size, and capacity.
私有变量是字符串* array,大小和容量。
You can use strcmp(string a, string b) in '<' overloading implementation. 您可以在'<'重载实现中使用strcmp(string a,string b)。
class ClassName{
/*
variables
constructors and methods
*/
bool operator<(ClassName obj){
ClassName obj1;
if(strcmp(obj.str , obj1.str)<0) //less than zero as we are overloading "<" operator
return true; //read - www.cplusplus.com/reference/cstring/strcmp
return false;
}
};
Similarly the ">" operator can be overloaded 同样,“>”运算符可以重载
The idea of a lexographical comparison between two sequences is that you sort the sequences first by their first element, and if necessary then by their second, etctera. 在两个序列之间进行字典比较的思想是,您首先按序列的第一个元素对序列进行排序,然后根据需要对它们进行第二个排序,以此类推。 That is to say, if
a[0]<b[0]
then a<b
. 也就是说,如果
a[0]<b[0]
则a<b
。 If a[0]>b[0]
, then a>b
. 如果
a[0]>b[0]
,则a>b
。 But if a[0]==b[0]
, then you look at a[1]
and b[1]
. 但是,如果
a[0]==b[0]
,那么您会看a[1]
和b[1]
。
When the sequence is a sequence of characters (aka string), this is the common dictionary order. 当序列是字符序列(又称字符串)时,这是常见的字典顺序。 But the same algorithm works on any sequence of sortable elements.
但是,相同的算法适用于任何可排序元素序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.