Asymmetry of string :: find_first_of and string :: find_last_of

With the member function member :: find_first_of in the C ++ Standard Library, you can search in an empty substring:

 s.find_first_of(c, s.size())

      

or

s.find_first_of(c, string::npos)

      

But you cannot search in an empty substring with string::find_last_of

; the next call will search in a substring containing (only) the first character:

 s.find_last_of(c, 0)

      

I think this is an imperfection of the C ++ Standard Library, right?

+3


source to share


1 answer


I don't see any asymmetry here. In fact, the opposite is true, it looks completely symmetrical. Think of it find_first_of

as searching to the right of some original position, and find_last_of

it is searching to the left of some original position.

The name find_last_of

has a deceiving quality: it implies a natural direct search, except that we return the last occurrence instead of the first. However, with bidirectional sequences, you can ignore the "forward" nature of the name and think of it as a reverse lookup. The reverse search also returns the first occurrence, it just goes to the left of the starting point. From this point of view, the function is symmetric with find_first_of

.

EDIT: After reading your comments, I finally understand your point. So the problem is that the current semantics of the parameter pos

does not allow you to specify an empty search scope for find_last_of

. Yes, it makes sense. I agree, this is indeed what can be seen as a design mismatch find_last_of

.

For consistency purposes, I would really expect find_last_of

not inclusive with respect to value pos

. In this case, the specification of the target position xpos

returned find_last_of

will be

xpos <pos and xpos <size ();



In this case, it s.find_last_of(c, 0)

will search for an empty prefix, but s.find_last_of(c, s.size())

will search for the entire string.

However, the standard says

xpos <= pos and xpos <size ();

I really don't know why they decided to give the parameter pos

such an inclusive meaning. They probably thought it would make it easier to understand.

+4


source







All Articles