2

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?

Mushy
  • 2,535
  • 10
  • 33
  • 54

3 Answers3

7

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.

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
5

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.

hmjd
  • 120,187
  • 20
  • 207
  • 252
4

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());
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434