principlecppCritical
Differences between C++ string == and compare()?
Viewed 0 times
andbetweendifferencesstringcompare
Problem
I just read some recommendations on using
instead of
I'm almost always using the last one because I'm used to it and it feels natural, more readable. I didn't even know that there was a separate comparison function.
To be more precise, I thought == would call compare().
What are the differences? In which contexts should one way be favored to the other?
I'm considering only the cases where I need to know if a string is the same value as another string.
std::string s = get_string();
std::string t = another_string();
if( !s.compare(t) )
{instead of
if( s == t )
{I'm almost always using the last one because I'm used to it and it feels natural, more readable. I didn't even know that there was a separate comparison function.
To be more precise, I thought == would call compare().
What are the differences? In which contexts should one way be favored to the other?
I'm considering only the cases where I need to know if a string is the same value as another string.
Solution
This is what the standard has to say about
21.4.8.2 operator==
Returns: lhs.compare(rhs) == 0.
Seems like there isn't much of a difference!
operator==21.4.8.2 operator==
template
bool operator==(const basic_string& lhs,
const basic_string& rhs) noexcept;Returns: lhs.compare(rhs) == 0.
Seems like there isn't much of a difference!
Code Snippets
template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs) noexcept;Context
Stack Overflow Q#9158894, score: 603
Revisions (0)
No revisions yet.