[Solved] Question about std::equal

Started by
8 comments, last by SiCrane 17 years, 8 months ago
Heya, currently i'm trying to write my own litle string tool lib and came across a problem with the using of std::equal. I've wrote a non-case string comparison functor to use with std::equal, which works just fine. The thing is, i've got a runtime error if i'm trying to compare strings with unequal length like:

// my functor
template <class T> class StrComp_NoCase
 {
  public :
   Bool operator () (const T & a, const T & b) const {
     return (tolower (a) == tolower (b));
    }
 };


string a ("String 1234");
string b ("STRING 1");

Bool bEqual = std::equal (a.begin(), a.end(), b.begin(), StrComp_NoCase<Char>()); <-- crashed badly

Bool bEqual = std::equal (b.begin(), b.end(), a.begin(), StrComp_NoCase<Char>()); <-- works just fine but gives me true back wich isnt exactly right



I mean i understand why the second version does work, because std::equal iterates over the smaler string and therefor dosen't pass the boundaries. But why is std::equal not testing if one of the strings isn't as long as the other and take that into account by just giving false back because they never can equal, ever. Oo Maybe i just missing the whole point of std::equal tho ... i hope someone can enlighten me on this one :) Thanks in advance. Mfg Impz0r [Edited by - Impz0r on July 22, 2006 2:21:01 PM]
Stay Evil & Ugly!
Advertisement
If the strings are of different size you already know that they are unequal. equal() is intended for when the ranges are of equal size.
Yeah thats correct, i just thought that std::equal do test this before it goes to work. Well, i think i've to write my own comparison function then.

Thanks anyway :)
Stay Evil & Ugly!
Why don't you just do it all in one function?
Quote:Original post by Impz0r
Yeah thats correct, i just thought that std::equal do test this before it goes to work. Well, i think i've to write my own comparison function then.

Thanks anyway :)


It can't "do this test", as you only send it b.begin(), it cannot compute b's length from just the starting position alone.
@rip-off

Yeah you're absolutely right, didn't thought of that. Then again, a equal function which takes also the end iterator of the second param would be nice :)


@raz0r

Do you mean within my comparison functor ? Or just a function like :

Bool cmp_nocase (const string &a, const string &b) { // do the stuff }



Well, thats what im doing right now :)


Mfg Impz0r
Stay Evil & Ugly!
Yes.
It's quite easy to write a variant of equal that checks length too:
template<class T1, class T2, class pb> bool myequal(T1 b1, T1 e1, T2 b2, T2 e2, pb pred){  return std::distance(b1,e1)==std::distance(b2,e2) && std::equal(b1,e1,b2,pred);}
Thanks Trap thats a nice solution!
Stay Evil & Ugly!
Just make sure you only pass it forward iterators, or bad things could happen.

This topic is closed to new replies.

Advertisement