查找失败时提升string_algo返回值

时间:2011-04-29 13:08:55

标签: c++ string boost find iterator-range

我想首先使用boost :: string_algo找到第一个空格:

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

我似乎无法在文档中找到任何内容,但如果它找不到空格则会返回该内容。我是否需要针对line.end()或其他东西测试token_range.end()?

谢谢!

1 个答案:

答案 0 :(得分:4)

我认为你应该像这样测试token_range.empty()

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

boost::iterator_range还有一个bool转换运算符,所以你甚至可以删除empty()函数调用,只需写:

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