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

25,288

Solution 1

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.

Solution 2

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));

Solution 3

LongInt::LongInt( const string v ) : val(v.begin(), v.end())
{
}
Share:
25,288
Ctak
Author by

Ctak

Updated on July 09, 2022

Comments

  • Ctak
    Ctak almost 2 years

    Right 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!