문제

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
}
도움이 되었습니까?

해결책 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;
}

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top