Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the less than comparison operator for strings

I'm following a tutorial for C++ and looking at strings and overloading with operators such as +=, ==, != etc. Currently I have a simple if-statement:

if(s1 < s2)
    cout << s2 <<endl;
else
  if(s2 < s1)
    cout << s1 << endl;
  else
    cout << "Equal\n";

But how does this work, and how does the program decide which string is greater than another? looking around I've found a basic template declaration:

template<class charT, class traits, class Allocator>
bool operator< ( const basic_string<charT,traits,Allocator>& lhs,
                 const basic_string<charT,traits,Allocator>& rhs );

Does this define how < works? If so, what does <charT,traits,Allocator> mean / do?

Also do the following operators have any meaning for strings? -= and *=

like image 507
Dmist Avatar asked Dec 11 '12 22:12

Dmist


People also ask

How do you compare less than in string?

Java String compareTo() Method The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters).

Can you use comparison operators on strings?

The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.

Can we use == operator for strings?

Using the == operator compares the object reference. Using the equals() method compares the value of the String . The same rule will be applied to all objects. When using the new operator, a new String will be created in the String pool even if there is a String with the same value.


2 Answers

The less-than operator on strings does a lexicographical comparison on the strings. This compares strings in the same way that they would be listed in dictionary order, generalized to work for strings with non-letter characters.

For example:

"a" < "b"
"a" < "ab"
"A" < "a"             (Since A has ASCII value 65; a has a higher ASCII value)
"cat" < "caterpillar"

For more information, look at the std::lexicographical_compare algorithm, which the less-than operator usually invokes.

As for -= and *=, neither of these operators are defined on strings. The only "arithmetic" operators defined are + and +=, which perform string concatenation.

Hope this helps!

like image 174
templatetypedef Avatar answered Oct 18 '22 06:10

templatetypedef


The comparison operators implement lexicographic ordering of strings.

-= and *= are not defined for strings.

like image 38
NPE Avatar answered Oct 18 '22 05:10

NPE