Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tell `string::operator==` to start comparing at the back of the string

Is it possible/(relatively) easy/std™ to start comparing at the back of a string or should I write my own function for that? It would be relatively straightforward of course, but still, I would trust a standard library implementation over mine any day.

The end of the string is almost unique, and the front is quite common, that's the only reason I need this "optimization".

Thanks!

like image 455
rubenvb Avatar asked Nov 30 '10 19:11

rubenvb


2 Answers

Best I can think of so far is str1.size() == str2.size() && std::equal(str1.rbegin(), str1.rend(), str2.rbegin())

like image 156
Steve Jessop Avatar answered Nov 03 '22 00:11

Steve Jessop


You could use std::equal in combination with std::basic_string::reverse_iterator (rbegin, rend).

However, it is relevant only if the strings have the same lenght (so you need first to check the sizes) and only for equality of the strings (since the most significant difference will be the last compared while iterating).

Example:

bool isEqual = s1.size() == s2.size() && std::equal( s1.rbegin(), s1.rend(), s2.rbegin());
like image 41
Cătălin Pitiș Avatar answered Nov 03 '22 00:11

Cătălin Pitiș