Use std::lexicographical_compare for less-than comparison:
bool const lt = std::lexicographical_compare(s1.begin(), s1.end(),
s2.begin(), s2.end());
For equality comparison you can use std::equal:
bool const e = s1.length() == s2.length() &&
std::equal(s1.begin(), s1.end(), s2.begin());
Alternatively, you can just fall back on strcmp (or actually memcmp, since that has the correct semanÂtics; remember that the C++ string is more general than a C string), as you suggested, which can potenÂtially employ some lower-level magic like comparing an entire machine word at a time (though the above algorithm may also be specialized thus). Measure and compare, I’d say. For short strings, the standard library algorithms are at least nicely self-descriptive.
Based on @Dietmar’s idea below, you could wrap those functions into a templated overload:
#include <string>
#include <algorithm>
template <typename TChar,
typename TTraits1, typename TAlloc1,
typename TTraits2, typename TAlloc2>
bool operator==(std::basic_string<TChar, TTraits1, TAlloc1> const & s1,
std::basic_string<TChar, TTraits2, TAlloc2> const & s2)
{
return s1.length() == s2.length() &&
std::equal(s1.begin(), s1.end(), s2.begin());
}
Usage example:
#include <ext/malloc_allocator.h>
int main()
{
std::string a("hello");
std::basic_string<char, std::char_traits<char>, __gnu_cxx::malloc_allocator<char>> b("hello");
return a == b;
}
In fact, you could define such an overload for most standard containers. You could even template it on a template, but that would be extreme.