Search code examples
c++boostlastindexof

boost::algorithm::string::finder.hpp


Already asked this question and received answers about c++ STL but what about boost?

This is a question about boost Finders. If you have a link to describable boost library implementations I would appreciate it to make hunting the boost library for practical applications easier.

My question is which boost finder most applies to lastIndexOf?


Solution

  • Well first off, the simplest option if you're going to search for the last occurrence of a substring is to use std::string::rfind:

    std::string str = "Hello, World!";
    int index = str.rfind("o");
    

    If you need to use Boost because you want it to work on generic ranges, use boost::algorithm::find_last. It takes two ranges. The second range is searched for in the first range.

    std::string str = "Hello, World!";
    iterator_range<std::string::iterator> it = find_last(str, "o");
    int index = std::distance(str.begin(), it.begin());
    

    If you really want to user a finder, it seems like you're looking for boost::algorithm::last_finder. The finders return a function object that takes two iterators as its arguments. The function returns an iterator_range You can use it like so:

    auto finder = last_finder("o");
    
    std::string str = "Hello, World!";
    iterator_range<std::string::iterator> it = finder(str.begin(), str.end());
    int index = std::distance(str.begin(), it.begin());