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;
}
C++ - How to convert char* to std::list<char>
Question
This is a beginner type of question
I'm just wondering if there is a way to convert a null terminated char* to std::list.
Thank you
char* data = ...
std::list<char> clist = convert_chars2list(data);
...
convert_chars2list(char* somedata)
{
//convert
}
La solution 2
Autres conseils
This is probably the simplest way:
#include <list>
#include <string>
int main()
{
char const* data = "Hello world";
std::list<char> l(data, data + strlen(data));
}
It exploits the fact that std::string
has an interface which is compatible with STL containers.
std::list<char> convert_chars2list(char* somedata)
{
std::list<char> res;
while (*somedata)
res.push_back(*somedata++);
return res;
}
If your char*
is a C-style string than you can do this (that means it ends with a \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] );
}
}
It's really weird to use a std::list to contain characters, if you really want to use stl to contain characters, you could use std::string, which would allow you to do:
char* data = ....;
std::string string(data);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow