On 18.06.2019 23:36, G G wrote:
> any hope of a change to mean
>
> -------------
>
> given strings : stringOne, stringTwo are equal
>
> that strcmp( stringOne, stringTwo ) will return true with a value of 1 or
> bool = true
> --------------
>
> given strings: stringOne, stringTwo are not equal
>
> that strcmp( stringOne, stringTwo ) will return false with a value of 0 or
> bool = false
>
> and maybe a new function strcmpOrder( string string1, string string2 )
> where if string1 comes before string2 returns a 1
>
> if not return 0;
The functions you mention are for comparing C strings, zero-terminated
strings represented by pointers.
Up at the C++ level `strcmp` corresponds to `std::string::compare`.
But `std::string` also offers the usual relational operators, like `==`,
`>` and so on, and the easiest way to get that notation for strings is
to just use `std::string`.
> sorry, just as i'm reading chapter 4, and was into'ed to strcmp
> i was just thinking...
>
> lol
>
> there is probably something better to come 14 more chapters to go.
>
> :-)
Hm, which book?
Anyway, the `strcmp`, `memcmp`, `std::string::compare` family of
functions, or at least the concept they embody, are about to have a
renaissance with the introduction of the spaceship operator in C++20.
The concept is roughly this: since the non-zero result values are not
specified one can use *any* values, and for example lexicographically
compare two struct instances this way:
struct S{ int x; int y; int z; };
auto compare( const S& a, const S& b )
-> int
{
if( const int r = a.x - b.x ) { return r; }
if( const int r = a.y - b.y ) { return r; }
if( const int r = a.z - b.z ) { return r; } // Redundant, but.
return 0;
}
Then the relational operators can easily and efficiently be expressed in
terms of, and automatically generated from, the single compare function.
A manual definition of one of them:
auto operator<( const S& a, const S& b )
-> bool
{ return compare( a, b ) < 0; }
If you try to express this function directly, without a function like
compare doing the brunt work, then you get into complexity where it's
very easy to step wrong, and then e.g. standard collections don't work.
That problem is reduced, though, when one learns about the `std::tuple`
based workaround,
auto operator<( const S&a, const S&b )
-> bool
{
using std::tie;
return tie( a.x, a.y, a.z ) < tie( b.x, b.y, b.z );
}
Here the `std::tuple::operator<` does the work, guaranteed correctly,
although possibly not as efficiently as compare. But on the third hand
with modern computers efficiency is no longer a matter of counting basic
operations. So it might be just as efficient, or even more.
It's just very much more work to do, with much redundancy, in general.
Cheers & hth.,
- Alf