list::assign (STL Samples)

Illustrates how to use the list::assign Standard Template Library (STL) function in Visual C++.

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;

Remarks

备注

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

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.

Example

// assign.cpp 
// compile with: /EHsc
//
// Shows 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;

int 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";
}

Output

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

Requirements

Header: <list>

See Also

Concepts

Standard Template Library Samples