C++: Comparing strings lexicographical
Asked Answered
S

1

6

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?
Scofield answered 8/4, 2012 at 20:40 Comment(3)
yes they are the same it wouldn't make sense if string comparison was not performed lexographicallyParavane
@EdChum: actually, it could make sense. Some locales' comparison isn't lexicographical.Brodsky
@Brodsky Hmm, I guess so I tend to always think of these things in western(ASCII) land, cheers for the info.Paravane
B
8

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

Brodsky answered 8/4, 2012 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.