سؤال

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?

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

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.

Sure, you can use std::find with reverse_iterators. 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());
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top