从 const char* 到迭代器错误的"无已知转换" - 另一个例子

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

本文关键字:转换 另一个 char 迭代器 错误 const      更新时间:2023-10-16

我正在执行以下操作:

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> >’

现在,我看到了几个相关的问题,其中的答案是忘记了#include <algorithm>,但我已经包含了它。还有其他遗漏的包含吗,还是另一个问题?

正如编译器错误所说,没有办法从constchar*构建迭代器。您可以使用std::string:来修复它

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

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

#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和其他实用程序的更多信息。

当然,如果您有Guidelines Support Library的实现,请从那里使用string_span(也称为string_view)(这里有一个实现)。它甚至可能进入标准库。

更新: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>('', ',', '"'));
相关文章: