开发者

C++ using STL List, how to copy an existing list into a new list

Righ开发者_StackOverflow社区t now I'm working with a copy constructor for taking a list called val of type char, and I need to take all the elements of a string v that is passed into the copy constructor and put them into the val list.

Public:
LongInt(const string v);

Private:
list<char> val;

So here in the public section of the LongInt class I have a copy constructor which takes the val list and copies the v string into it. Can anyone help me figure out how to do this? Thanks in advance!


You'll have to iterate over the string and extract the data character by character. Using the std::copy algorithm should work:

std::copy(v.begin(), v.end(), std::back_inserter(val));


In your LongInt constructor just use the iterator, iterator list constructor:

LongInt(const string v) : val(v.begin(), v.end()) { }

That being said, have you considered actually using string or possibly deque<char> to manipulate your sequence rather than list? Depending on your needs, those alternatives might be better.


LongInt::LongInt( const string v ) : val(v.begin(), v.end())
{
}


First, use std::string if it's a string you're storing. It's a container like any other. If you can't or don't want to store a string, use std::vector. But that would boil down to a less-functional std::string anyway, so just use std::string.

For the copying:

std::copy( v.begin(), v.end(), std::back_inserter(val) );

But just use a std::string if it's a list of chars you're storing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜