"no known conversion" 从 const char* 到迭代器错误 - 另一种方式

The "no known conversion" from const char* to an iterator error - another take

我正在执行以下操作:

using namespace boost;
const char* line = // ...
size_t line_length = // ...
// ...
tokenizer<escaped_list_separator<char> > line_tokenizer(
    line, line + line_length,
    escaped_list_separator<char>('\', ',', '\"'));

期望使用 boost::tokenizer 构造函数

tokenizer(Iterator first, Iterator last,
          const TokenizerFunc& f = TokenizerFunc()) 
  : first_(first), last_(last), f_(f) { }

但是 GCC 4.9.3 给了我:

no known conversion for argument 1 from ‘const char*’ to ‘__gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >’

现在,我已经看到一些 questions 的答案是忘记 #include <algorithm> - 但我 已经 包括了它。是否还有其他缺失的包含,或者是另一个问题?

正如编译器错误所说,无法从 const char* 构建迭代器。您可以使用 std::string:

修复它
std::string line = "some string";
// ...
tokenizer<escaped_list_separator<char> > line_tokenizer(
    line.begin(), line.end(),
    escaped_list_separator<char>('\', ',', '\"'));

如果您不想使用容器作为搜索,则必须手动构建令牌迭代器space

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>

int main()
{
    const char xx[] = "a,b,c,d,e,f,g";
    auto line = xx;
    size_t line_length = strlen(line);

    using namespace boost;

    auto f = escaped_list_separator<char>('\', ',', '\"');
    auto beg = make_token_iterator<char>(line ,line + line_length,f);
    auto end = make_token_iterator<char>(line + line_length,line + line_length,f);
    // The above statement could also have been what is below
    // Iter end;
    for(;beg!=end;++beg){
        std::cout << *beg << "\n";
    }
    return 0;
}

由于您使用的是 boost,因此您可以:

#include <boost/utility/string_ref.hpp>
// ...
const boost::string_ref line_(line, line_length);
tokenizer<escaped_list_separator<char> > line_tokenizer(
    line_, escaped_list_separator<char>('\', ',', '\"'));

这似乎行得通。详细了解 string_ref 和其他实用程序 here

当然,如果您有指南支持库的实现,请从那里使用 string_span(a.k.a。string_view)(here 的一个实现).它甚至可能进入标准库。

更新:string_view 在 C++17 的 C++ 标准中。现在你可以写:

#include <string_view>
// ...
std::string_view line_ { line, line_length };
tokenizer<escaped_list_separator<char> > line_tokenizer(
    line_, escaped_list_separator<char>('\', ',', '\"'));