Search code examples
c++stringboostfinditerator-range

boost string_algo return value on find failure


I want to find the first space on a line using boost::string_algo's find first:

const boost::iterator_range<std::string::iterator> token_range = boost::find_first(line, " ");

I can't seem to find anything in the docs that says what this returns if it doesn't find a space, though. Do I need to test token_range.end() against line.end() or something?

Thanks!


Solution

  • I think you should just test token_range.empty(), like this:

    const boost::iterator_range<std::string::iterator> token_range = boost::find_first(line, " ");
    if (!token_range.empty())
    {
        // Found a a match
    }
    

    boost::iterator_range also has a bool conversion operator, so you can even drop the empty() function call, and just write:

    const boost::iterator_range<std::string::iterator> token_range = boost::find_first(line, " ");
    if (token_range)
    {
        // Found a a match
    }