Question

Are strings compared lexicographical when using the overriden bool operator<(const std::string & rhs) operator? In example:

std::string str1 = "aabbcc"
std::string str2 = "bbaacc"

(str1 < str2) == std::lexicographical_compare(str1.begin(),str1.end(),str2.begin(),str2.end()) // is this statement true?
Was it helpful?

Solution

Yes.

String's comparison operators are defined in terms of its traits::compare (that is char_traits<char>::compare) (C++03 21.3.6.8) which is specified to return a value based on the lexicographical ordering of its arguments (21.1.1).

X::compare(p,q,n) ... yields: 0 if for each i in [0,n), X::eq(p[i],q[i]) is true; else, a negative value if, for some j in [0,n), X::lt(p[j],q[j]) is true and for each i in [0,j) X::eq(p[i],q[i]) is true; else a positive value.

In effect, it means comparing string must not be locale sensitive (which could be non-lexicographical in some locales, such as mine).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top