list::assign (STL Sample)

The sample code below illustrates how to use the list::assign STL function in Visual C++.

Required Header:
<list>

Prototype:

     void assign(const_iterator first, const_iterator last);
     void assign(size_type n, const T& x = T());
     iterator erase(iterator it);
     iterator erase(iterator first, iterator last);
     bool empty() const;

Note: The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.

Description:
The first member function replaces the sequence controlled by *this with the sequence [first, last). The second member function replaces the sequence controlled by *this with a repetition of n elements of value x. The third member function removes the element of the controlled sequence pointed to by it. The fourth member function removes the elements of the controlled sequence in the range [first, last). Both return an iterator that designates the first element remaining beyond any elements removed, or end() if no such element exists. The last member function returns true for an empty controlled sequence.

Sample Code:

//////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// assign.cpp :  Shows the various ways to assign and erase elements
//               from a list<T>.
//
// Functions:
//
//    list::assign
//    list::empty
//    list::erase
//////////////////////////////////////////////////////////////////////

#include <list>
#include <iostream>

using namespace std ;

typedef list<int> LISTINT;

void main()
{
    LISTINT listOne;
    LISTINT listAnother;
    LISTINT::iterator i;

    // Add some data
    listOne.push_front (2);
    listOne.push_front (1);
    listOne.push_back (3);

    listAnother.push_front(4);

    listAnother.assign(listOne.begin(), listOne.end());

    // 1 2 3
    for (i = listAnother.begin(); i != listAnother.end(); ++i)
        cout << *i << " ";
    cout << endl;

    listAnother.assign(4, 1);

    // 1 1 1 1
    for (i = listAnother.begin(); i != listAnother.end(); ++i)
        cout << *i << " ";
    cout << endl;

    listAnother.erase(listAnother.begin());

    // 1 1 1
    for (i = listAnother.begin(); i != listAnother.end(); ++i)
        cout << *i << " ";
    cout << endl;

    listAnother.erase(listAnother.begin(), listAnother.end());
    if (listAnother.empty())
        cout << "All gone\n";
}

 

Program Output is:

1 2 3
1 1 1 1
1 1 1
All gone