Reputation: 131
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
}
Upvotes: 1
Views: 3521
Reputation: 12761
Let C++ standard library take care of pointer handling and iterator traversing.
std::string str = "Hello world";
Though you can access each character with [] operator from std::string itself, if you want a list of characters
std::list<char> chars(str.begin(), str.end());
Upvotes: 0
Reputation: 126442
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.
Upvotes: 9
Reputation: 9843
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] );
}
}
Upvotes: 0
Reputation: 2422
std::list<char> convert_chars2list(char* somedata)
{
std::list<char> res;
while (*somedata)
res.push_back(*somedata++);
return res;
}
Upvotes: 1
Reputation: 444
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);
Upvotes: -1
Reputation: 10613
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;
}
Upvotes: 2