How does std::string::rfind work?

Hi, title is my question.

I would imagine that either the string gets temporarily reversed and he searches through the reversed string starting at position zero of the reversed string and searches for the given substring (which got also reversed).

Or he doesn't do anything with the string and simply starts searching at the last position of the string, going backwards until the given substring is found.

But the documentation I found so far leads me to believe that he actually searches through the untouched string starting at position zero and going all the way to the end, returning the last occurence of the substring. However that would be somewhat illogical, right?
I mean in this case, what would be the difference to string::find_last_of?

Am I right with one of these assumptions or does it work differently?

In any case, string::rfind should always be faster than string::find if I search through a string and the wanted substring is at the end of the string he searches through or?
I mean I could also use for example string::find with the start position in the last quarter of the string when I know for sure that the beginning of my wanted substring is located there (and goes all to the end) but would that be faster than simply using string::rfind?

I'm asking this because I couldn't really find anything specific about the functionality of string::rfind and I would like to know when it's better to use it.
Last edited on
rfind() finds last occurence of substring. find_last_of() finds the last character equal to one of characters in substring (ANY!)
#include <iostream>
#include <string>

int main()
    std::string x = "type type";
    auto y = x.rfind("type");
    auto z = x.find_last_of("pyt");
    std::cout << y << " "; //5, points to first character of second "type"
    std::cout << z; //7, points to "p", last character which contains in "pyt" 

: AFAIK exact alghoryhtm of rfind() is implementation defined.
Last edited on
Ok well I thought the algorithm would be a standardized one.

I guess I'll mark this as solved until someone else posts more info regarding this topic.
Topic archived. No new replies allowed.