这是一个初学者类型的问题
我只是想知道是否有办法将空终止的char *转换为std :: list。
谢谢
char* data = ...
std::list<char> clist = convert_chars2list(data);
...
convert_chars2list(char* somedata)
{
//convert
}
答案 0 :(得分:9)
这可能是最简单的方法:
#include <list>
#include <string>
int main()
{
char const* data = "Hello world";
std::list<char> l(data, data + strlen(data));
}
它利用std::string
具有与STL容器兼容的接口的事实。
答案 1 :(得分:2)
std::list<char> convert_chars2list(char *somedata)
{
std::list<char> l;
while(*somedata != 0)
l.push_back(*somedata++);
// If you want to add a terminating NULL character
// in your list, uncomment the following statement:
// l.push_back(0);
return l;
}
答案 2 :(得分:1)
std::list<char> convert_chars2list(char* somedata)
{
std::list<char> res;
while (*somedata)
res.push_back(*somedata++);
return res;
}
答案 3 :(得分:0)
如果您的char*
是C风格的字符串而不是您可以执行此操作(这意味着它以\0
结尾)
#include <list>
int main()
{
char hello[] = "Hello World!";
std::list<char> helloList;
for(int index = 0; hello[index] != 0; ++index)
{
helloList.push_back( hello[index] );
}
}
答案 4 :(得分:-1)
使用std :: list来包含字符真的很奇怪,如果你真的想用stl来包含字符,可以使用std::string,这样就可以了:
char* data = ....;
std::string string(data);