Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Jan 9, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Comparing Strings Efficiently

The standard string class offers three versions of the overloaded == operator:
  bool operator == (const string& left, const string right); 
  bool operator == (const char* left, const string right); 
  bool operator == (const string& left, const char* right); 
This proliferation may seem redundant, since string has a constructor that automatically converts a const char * to a string object. Thus, we could make do with only the first version of operator ==, which in turn converts a char * to a temporary string object, and then performs the comparison. However, overhead of creating a temporary string can be unacceptable under some circumstances. The temporary string has to allocate memory on the heap and copy the C-string. Finally, it has to release the allocated memory. The Standardization committee's intent was to make comparison of strings as efficient as possible. The additional overloaded versions were added to allow comparisons to be made directly, without the additional overhead of temporaries.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date