问题
I performed some research on boost and c++ but could not locate anything relevant to my question. Is there an boost library or STL function that implements lastIndexOf?
回答1:
std::string
has the member function rfind() which searches from the end and returns the index if found or std::string::npos
if not. From the linked reference page:
Finds the last substring equal to the given character sequence.
回答2:
It looks like you might want std::string::find_last_of.
Finds the last character equal to one of characters in the given character sequence. Returns the position of the found character or npos if no such character is found.
Edit:
Also see hmjd's answer. There are differences between find_last_of
and rfind
depending on whether you are searching for a single character, one of many possible characters, or a substring.
回答3:
Sure, you can use std::find
with reverse_iterator
s. For example, you have a vector of ints and you want to find the last 5 in it. You do
auto it = std::find(v.rbegin(), v.rend(), 5);
If you want the index per se, then you can get that from the iterator
int index = std::distance(v.begin(), (it+1).base());
来源:https://stackoverflow.com/questions/15557700/java-like-lastindexof-in-c