C ++ string comparison

#include "stdafx.h" #include "iostream" #include "string" using namespace std; void main() { string a = "a"; string b(1, -70); /*constructor, create a string having 1 character that its value is equal to -70*/ cout<<((b>a)?b:a); } //output on screen: b was printed, not a (!) 

Why b> a, although b is less than a? How can I fix this?

+4
source share
3 answers

On VS2010, I found that char was signed - hence, not a desirable explanation. After going through the debugger during the comparison, I eventually hit the code:

 template<> struct char_traits<char> { // properties of a string or stream char element typedef char _Elem; typedef _Elem char_type; typedef int int_type; typedef streampos pos_type; typedef streamoff off_type; typedef _Mbstatet state_type; static int __CLRCALL_OR_CDECL compare(const _Elem *_First1, const _Elem *_First2, size_t _Count) { // compare [_First1, _First1 + _Count) with [_First2, ...) return (_CSTD memcmp(_First1, _First2, _Count)); } // etc }; 

So the real comparison comes down to memcmp . By checking this, we find "evaluated as unsigned char", hence the problem.

Cf. Reply to Arytom. Interestingly, I did not know this. Looking at this:

The 1998 standard 21.1.3.1:6 is defined identically to the built-in operator <by char_traits 'lt' states.

Project N3126, 21.2.3.1.5 says that it should be like for an unsigned char.

+3
source

Strings are always compared as unsigned char regardless of the sign of the actual character.

std::string took this behavior with C, where strcmp uses characters in the range 0-255, even if char is in the range -128 - 127.

So basically -70 - 186 and 186> 'a'

Edit: Link to standard. I don't have C ++ 98/2003 next to me, only C ++ 0x, but:

β€œWorking draft, standard for the C ++ programming language”, N2915, 21.2.3.1, note 5 states:

Elements with two arguments eq and lt must be defined identically to the built-in operations == and <for type unsigned char.

i.e. characters are compared as unsigned char. (he refers to character traits specialization for char)

+2
source

See the binary equivalent value of -70 as 1 character.

+1
source

Source: https://habr.com/ru/post/1333132/


All Articles