从 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> >’
现在,我看到了几个相关的问题,其中的答案是忘记了#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>('', ',', '"'));
相关文章:
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- 如果需要转换,我可以在读取参数的同时将其移动到另一个参数吗?
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- 如何从一个容器中获取某些元素并将其转换插入到另一个容器中?
- 以最少的步骤将给定整数转换为另一个整数
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 尝试向 COM 对象添加另一个接口时出现静态强制转换错误 C2440
- 返回带有另一个类的数据成员的构造函数?遇到转换错误?
- 另一个:从"常量类型*"到"类型*"的转换无效
- 将 lambda 函数转换为另一个编译单元中的普通函数会缩短编译时间吗?
- 将其转换为共享指针,并将其作为参数传递给另一个C++类
- 将 std::variant 转换为另一个具有类型子集的 std::variant
- C++字符串类如何将一个变量转换为另一个变量?
- C++将时间从一个环境转换为另一个环境
- 转换运算符从一个模板类到另一个相关的模板类
- C 将类的实例转换为另一个
- 为什么将好奇模板模式的基类直接转换为另一个基类是错误的?
- 如何转换一个类方法以修改另一个类的私有元素?
- 一种体面的方式来转换const列表参考参数,然后传递到另一个函数
- 从 const char* 到迭代器错误的"无已知转换" - 另一个例子