std::list

List

Lists are a kind of sequence containers. As such, their elements are ordered following a linear sequence.
列表是一种序列容器。因此,它们的元素是按照线性序列排列的。

List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they contain in different and unrelated storage locations. The ordering is kept by the association to each element of a link to the element preceding it and a link to the element following it.
列表容器被实现为双链表;双链接列表可以将它们包含的每个元素存储在不同且不相关的存储位置。排序是通过与前面元素的链接和后面元素的链接中的每个元素的关联来保持的。

This provides the following advantages to list containers:


Efficient insertion and removal of elements anywhere in the container (constant time). 
元件在容器中任何位置的有效插入和移除(恒定时间)。
Efficient moving elements and block of elements within the container or even between different containers (constant time). 
在容器内或甚至在不同容器之间高效地移动元件和元件块(恒定时间)。
Iterating over the elements in forward or reverse order (linear time). 
按正向或反向顺序(线性时间)对元素进行迭代。
Compared to other base standard sequence containers (vectors and deques), lists perform generally better in inserting, extracting and moving elements in any position within the container, and therefore also in algorithms that make intensive use of these, like sorting algorithms.
与其他基本标准序列容器(向量和deques)相比,列表在插入、提取和移动容器内任何位置的元素方面通常表现得更好,因此在密集使用这些元素的算法(如排序算法)中也表现得更好。

The main drawback of lists compared to these other sequence containers is that they lack direct access to the elements by their position; For example, to access the sixth element in a list one has to iterate from a known position (like the beginning or the end) to that position, which takes linear time in the distance between these. They also consume some extra memory to keep the linking information associated to each element (which may be an important factor for large lists of small-sized elements).
与这些其他序列容器相比,列表的主要缺点是它们无法通过位置直接访问元素;例如,要访问列表中的第六个元素,必须从已知位置(如开头或结尾)迭代到该位置,这需要这些位置之间的线性时间。它们还消耗一些额外的内存来保持与每个元素相关联的链接信息(这可能是小型元素的大列表的重要因素)。

Storage is handled automatically by the class, allowing lists to be expanded and contracted as needed.
存储由类自动处理,允许根据需要扩展和收缩列表。

In their implementation in the C++ Standard Template Library lists take two template parameters:
template < class T, class Allocator = allocator<T> > class list;
 在C++标准模板库中的实现中,列表采用两个模板参数:
template<class T,class Allocator=分配器<T>>类列表;

Where the template parameters have the following meanings:


T: Type of the elements. 
Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent. 
In the reference for the list member functions, these same names are assumed for the template parameters.
T: 元素的类型。
分配器:用于定义存储分配模型的分配器对象的类型。默认情况下,使用类型T的分配器类模板,它定义了最简单的内存分配模型,并且与值无关。
在列表成员函数的引用中,模板参数采用了这些相同的名称。

list

explicit list ( const Allocator& = Allocator() );
explicit list ( size_type n, const T& value = T(), const Allocator& = Allocator() );
template < class InputIterator >
         list ( InputIterator first, InputIterator last, const Allocator& = Allocator() );
list ( const list<T,Allocator>& x );  

Construct list

Constructs a list container object, initializing its contents depending on the constructor version used:


explicit list ( const Allocator& = Allocator() ); 
Default constructor: constructs an empty list object, with no content and a size of zero. 
explicit list ( size_type n, const T& value= T(), const Allocator& = Allocator() ); 
Repetitive sequence constructor: Initializes the container object with its content set to a repetition, n times, of copies of value. 
template <class InputIterator> list ( InputIterator first, InputIterator last, const Allocator& = Allocator() ); 
Iteration constructor: Iterates between first and last, setting a copy of each of the sequence of elements as the content of the container object. 
list ( const list<T,Allocator>& x ); 
Copy constructor: The object is initialized to have the same contents and properties as the x list object. 

Parameters
n 
Times that value is repeated to form the content of the object.
Member type size_type is an unsigned integral type. 
value 
Value to be repeated n times as the content of the object.
T is the first class template parameter (the type of the elements stored in the list). 
first, last 
Input iterators to the initial and final positions in a sequence. The range used is [first,last), which includes all the elements between first and last, including the element pointed by first but not the element pointed by last.
The function template type can be any type of input iterator. 

x 
Another list object with the same class template parameters (T and Allocator).

unnamed Allocator parameter 
Allocator object to be used instead of constructing a new one.
For class instantiations using their version of the default allocator class template, this parameter is not relevant. 

Example
// constructing lists
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  // constructors used in the same order as described above:
  list<int> first;                                // empty list of ints
  list<int> second (4,100);                       // four ints with value 100
  list<int> third (second.begin(),second.end());  // iterating through second
  list<int> fourth (third);                       // a copy of third

  // the iterator constructor can also be used to construct from arrays:
  int myints[] = {16,2,77,29};
  list<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

  cout << "The contents of fifth are: ";
  for (list<int>::iterator it = fifth.begin(); it != fifth.end(); it++)
    cout << *it << " ";

  cout << endl;

  return 0;
}
 
Output:
The contents of fifth are: 16 2 77 29  

operator=

list<T,Allocator>& operator= ( const list<T,Allocator>& x );  

Copy container content

Assigns as the new content for the container a copy of the elements in x.

The elements contained in the object before the call are dropped, and replaced by copies of those in vector x, if any.

After a call to this member function, both the list object and x will have the same size and compare equal to each other.


Parameters
x 
A list object containing elements of the same type. 

Return value
*this

Example
// assignment operator with lists
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> first (3);      // list of 3 zero-initialized ints
  list<int> second (5);     // list of 5 zero-initialized ints

  second=first;
  first=list<int>();

  cout << "Size of first: " << int (first.size()) << endl;
  cout << "Size of second: " << int (second.size()) << endl;
  return 0;
}
 
Both list containers of int elements are initialized to sequences with different sizes. Then, second is assigned to first, so both are now equal and with a size of 3. And then, first is assigned to a newly constructed empty container object, so its size is finally 0. Output:
Size of first: 0
Size of second: 3 


Complexity
Linear on sizes (destruction, copy construction).

begin/end

 iterator begin ();
const_iterator begin () const;  

Return iterator to beginning

Returns an iterator referring to the first element in the list container.


Parameters
none

Return Value
An iterator to the beginning of the sequence.
Both iterator and const_iterator are member types. In the list class template, these are bidirectional iterators.


Example
// list::begin
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  int myints[] = {75,23,65,42,13};
  list<int> mylist (myints,myints+5);

  list<int>::iterator it;

  cout << "mylist contains:";
  for ( it=mylist.begin() ; it != mylist.end(); it++ )
    cout << " " << *it;

  cout << endl;

  return 0;
}
 

Output:
mylist contains: 75 23 65 42 13 

rbegin/rend

reverse_iterator rbegin();
const_reverse_iterator rbegin() const;   

Return reverse iterator to reverse beginning

Returns a reverse iterator referring to the last element in the list container.

rbegin refers to the element right before the one that would be referred to by member end.


Parameters
none

Return Value
A reverse iterator to the reverse beginning of the sequence.
Both reverse_iterator and const_reverse_iterator are member types. In the list class template, these are reverse bidirectional iterators, defined as reverse_iterator<iterator> and reverse_iterator<const_iterator> respectivelly.


Example
// list::rbegin/rend
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;
  for (int i=1; i<=5; i++) mylist.push_back(i);

  cout << "mylist contains:";
  list<int>::reverse_iterator rit;
  for ( rit=mylist.rbegin() ; rit != mylist.rend(); ++rit )
    cout << " " << *rit;

  cout << endl;

  return 0;
}
 

Output:
mylist contains: 5 4 3 2 1 

empty

bool empty ( ) const;  

Test whether container is empty

Returns whether the list container is empty, i.e. whether its size is 0.

This function does not modify the content of the container in any way. To clear the content of a list container, use list::clear.


Parameters
none

Return Value
true if the container size is 0, false otherwise.

Example
// list::empty
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;
  int sum (0);

  for (int i=1;i<=10;i++) mylist.push_back(i);

  while (!mylist.empty())
  {
     sum += mylist.front();
     mylist.pop_front();
  }

  cout << "total: " << sum << endl;
  
  return 0;
}
 
The example initializes the content of the container to a sequence of numbers (form 1 to 10). It then pops the elements one by one until it is empty and calculates their sum.
Output:
total: 55 


size

size_type size() const;   

Return size

Returns the number of elements in the container.


Parameters
none

Return Value
The number of elements that conform the list's content.
Member type size_type is an unsigned integral type.


Example
// list::size
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> myints;
  cout << "0. size: " << (int) myints.size() << endl;

  for (int i=0; i<10; i++) myints.push_back(i);
  cout << "1. size: " << (int) myints.size() << endl;

  myints.insert (myints.begin(),10,100);
  cout << "2. size: " << (int) myints.size() << endl;

  myints.pop_back();
  cout << "3. size: " << (int) myints.size() << endl;

  return 0;
}
 

Output:
0. size: 0
1. size: 10
2. size: 20
3. size: 19 

max_size

size_type max_size () const;  

Return maximum size

Returns the maximum number of elements that the list container can hold.

This is the maximum potential size the container can reach due to system or library implementation limitations.


Parameters
none

Return Value
The maximum number of elements a list container can have as its content.
Member type size_type is an unsigned integral type.


Example
// list::max_size
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  unsigned int i;
  list<int> mylist;

  cout << "Enter number of elements: ";
  cin >> i;

  if (i<mylist.max_size()) mylist.resize(i);
  else cout << "That size exceeds the limit.\n";

  return 0;
}
 

resize

void resize ( size_type sz, T c = T() );  

Change size

Resizes the container to contain sz elements.

If sz is smaller than the current container size, the content is reduced to its first sz elements, the rest being dropped.

If sz is greater than the current container size, the content is expanded by inserting at the end as many copies of c as needed to reach a size of sz elements.

Notice that this function changes the actual content of the container by inserting or erasing elements from it.


Parameters
sz 
New container size, expressed in number of elements.
Member type size_type is an unsigned integral type. 
c 
Object whose content is copied to the added elements in case that sz is greater than the current container size.
If not specified, the default constructor is used.
T is the first template parameter (the type of the elements stored in the container). 

Return Value
none
In case of growth, the storage for the new elements is allocated using Allocator::allocate(), which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).


Example
// resizing list
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;

  unsigned int i;

  // set some initial content:
  for (i=1;i<10;i++) mylist.push_back(i);

  mylist.resize(5);
  mylist.resize(8,100);
  mylist.resize(12);

  cout << "mylist contains:";
  for (list<int>::iterator it=mylist.begin();it!=mylist.end();++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}
 

The code sets a sequence of 9 numbers as an initial content for mylist. It then uses resize first to set the container size to 5, then to extend its size to 8 with values of 100 for its new elements, and finally it extends its size to 12 with their default values (for int elements this is zero).
Output:
mylist contains: 1 2 3 4 5 100 100 100 0 0 0 0 

front 

 reference front ( );
const_reference front ( ) const;  

Access first element

Returns a reference to the first element in the list container.

Unlike member list::begin, which returns an iterator to this same element, this function returns a direct reference.


Parameters
none

Return value
A reference to the first element in the list container.
Member types reference and const_reference are the reference types to the elements of the container (for the default storage allocation model, allocator, these are T& and const T& respectively).


Example
// list::front
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;

  mylist.push_back(77);
  mylist.push_back(16);

  // now front equals 77, and back 16

  mylist.front() -= mylist.back();

  cout << "mylist.front() is now " << mylist.front() << endl;

  return 0;
}
 

Output:
mylist.front() is now 61 

back

 reference back ( );
const_reference back ( ) const;   

Access last element

Returns a reference to the last element in the container.

Unlike member list::end, which returns an iterator just past this element, this function returns a direct reference.


Parameters
none

Return value
A reference to the last element in the list container.
Member types reference and const_reference are the reference types to the elements of the container (for the default storage allocation model, allocator, these are T& and const T& respectively).


Example
// list::back
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;

  mylist.push_back(10);

  while (mylist.back() != 0)
  {
    mylist.push_back ( mylist.back() -1 );
  }

  cout << "mylist contains:";
  for (list<int>::iterator it=mylist.begin(); it!=mylist.end() ; ++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}
 

Output:
mylist contains: 10 9 8 7 6 5 4 3 2 1 0 

assign

template <class InputIterator>
  void assign ( InputIterator first, InputIterator last );
void assign ( size_type n, const T& u );  

Assign new content to container

Assigns new content to the container, dropping all the elements contained in the container object before the call and replacing them by those specified by the parameters:

In the first version (with iterators), the new contents of the container object is a copy of those contained in the sequence between first and last (in the range [first,last)).

In the second version, the new content is the repetition n times of copies of element u.


Parameters
first, last 
Input iterators to the initial and final positions in a sequence. The range used is [first,last), which includes all the elements between first and last, including the element pointed by first but not the element pointed by last.
The template type can be any type of input iterator. 
n 
Times that u is repeated to form the new content of the object.
Member type size_type is an unsigned integral type. 
u 
Value to be repeated n times as the new content of the object.
T is the first class template parameter (the type of the elements stored in the list container). 

Return value
none

Example
// list::assign
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> first;
  list<int> second;

  first.assign (7,100);                      // 7 ints with value 100

  second.assign (first.begin(),first.end()); // a copy of first

  int myints[]={1776,7,4};
  first.assign (myints,myints+3);            // assigning from array

  cout << "Size of first: " << int (first.size()) << endl;
  cout << "Size of second: " << int (second.size()) << endl;
  return 0;
}
 
Output:
Size of first: 3
Size of second: 7 

push_front

void push_front ( const T& x );  

Insert element at beginning

Inserts a new element at the beginning of the list, right before its current first element. The content of this new element is initialized to a copy of x.

This effectively increases the list size by one.


Parameters
x 
Value to be copied to the new element.
T is the first template parameter (the type of the elements stored in the container). 

Return value
none
The storage for the new element is allocated using Allocator::allocate(), which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).


Example
// list::push_front
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist (2,100);         // two ints with a value of 100
  mylist.push_front (200);
  mylist.push_front (300);

  cout << "mylist contains:";
  for (list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;

  cout << endl;
  return 0;
}
 

Output:
300 200 100 100  

pop_front

void pop_front ( );  

Delete first element

Removes the first element in the list container, effectively reducing the list size by one.

This calls the removed element's destructor.


Parameters
none

Return value
none

Example
// list::pop_front
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;
  int sum (0);
  mylist.push_back (100);
  mylist.push_back (200);
  mylist.push_back (300);

  cout << "Popping out the elements in mylist:";
  while (!mylist.empty())
  {
    cout << " " << mylist.front();
    mylist.pop_front();
  }

  cout << "\nFinal size of mylist is " << int(mylist.size()) << endl;

  return 0;
}
 
Output:
Popping out the elements in mylist: 100 200 300
Final size of mylist is 0 

push_back

void push_back ( const T& x );  

Add element at the end

Adds a new element at the end of the list, right after its current last element. The content of this new element is initialized to a copy of x.

This effectively increases the list size by one.


Parameters
x 
Value to be copied to the new element.
T is the first template parameter (the type of the elements stored in the container). 

Return value
none
The storage for the new element is allocated using Allocator::allocate(), which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).


Example
// list::push_back
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;
  int myint;

  cout << "Please enter some integers (enter 0 to end):\n";

  do {
    cin >> myint;
    mylist.push_back (myint);
  } while (myint);

  cout << "mylist stores " << (int) mylist.size() << " numbers.\n";

  return 0;
}
 

pop_back

void pop_back ( );  

Delete last element

Removes the last element in the list container, effectively reducing the list size by one.

This calls the removed element's destructor.


Parameters
none

Return value
none

Example
// list::pop_back
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;
  int sum (0);
  mylist.push_back (100);
  mylist.push_back (200);
  mylist.push_back (300);

  while (!mylist.empty())
  {
    sum+=mylist.back();
    mylist.pop_back();
  }

  cout << "The elements of mylist summed " << sum << endl;

  return 0;
}
 
In this example, the elements are popped out from the end of the list after they are added up in the sum. Output:
The elements of mylist summed 600 

insert

iterator insert ( iterator position, const T& x );
    void insert ( iterator position, size_type n, const T& x );
template <class InputIterator>
    void insert ( iterator position, InputIterator first, InputIterator last );  

Insert elements

The list container is extended by inserting new elements before the element at position.

This effectively increases the container size by the amount of elements inserted.

lists are sequence containers specifically designed to be efficient inserting and removing elements in any position, even in the middle of the sequence. Compared to the other base sequence containers (vector and deque), lists are the most efficient container doing insertions at some position other than the beginning or the end of the sequence, and, unlike in these, all of the previously obtained iterators and references remain valid after the insertion and refer to the same elements they were referring before.

The parameters determine how many elements are inserted and to which values they are initialized:


Parameters
position 
Position in the container where the new elements are inserted.
iterator is a member type, defined as a bidirectional iterator type. 
x 
Value to be used to initialize the inserted elements.
T is the first template parameter (the type of the elements stored in the container). 
n 
Number of elements to insert. Each element is initialized to the value specified in x.
Member type size_type is an unsigned integral type. 
first, last 
Iterators specifying a range of elements. Copies of the elements in the range [first,last) are inserted at position position.
Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
The template type can be any type of input iterator. 

Return value
Only the first version returns a value, which is an iterator that points to the newly inserted element.

Example
// inserting into a list
#include <iostream>
#include <list>
#include <vector>
using namespace std;

int main ()
{
  list<int> mylist;
  list<int>::iterator it;

  // set some initial values:
  for (int i=1; i<=5; i++) mylist.push_back(i); // 1 2 3 4 5

  it = mylist.begin();
  ++it;       // it points now to number 2           ^

  mylist.insert (it,10);                        // 1 10 2 3 4 5

  // "it" still points to number 2                      ^
  mylist.insert (it,2,20);                      // 1 10 20 20 2 3 4 5

  --it;       // it points now to the second 20            ^

  vector<int> myvector (2,30);
  mylist.insert (it,myvector.begin(),myvector.end());
                                                // 1 10 20 30 30 20 2 3 4 5
                                                //               ^
  cout << "mylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); it++)
    cout << " " << *it;
  cout << endl;

  return 0;
}
 
Output:
mylist contains: 1 10 20 30 30 20 2 3 4 5 

erase

iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );  

Erase elements

Removes from the list container either a single element (position) or a range of elements ([first,last)).

This effectively reduces the vector size by the number of elements removed, calling each element's destructor before.

lists are sequence containers specifically designed to be efficient inserting and removing elements in any position, even in the middle of the sequence. Compared to the other base sequence containers (vector and deque), lists are the most efficient container erasing at some position other than the beginning or the end of the sequence, and, unlike in these, all of the previously obtained iterators and references remain valid after the erasing operation and refer to the same elements they were referring before (except, naturally, for those referring to erased elements).


Parameters
All parameters are of member type iterator, which in list containers are defined as a bidirectional iterator type.

position 
Iterator pointing to a single element to be removed from the list. 
first, last 
Iterators specifying a range within the list container to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last. 

Return value
A bidirectional iterator pointing to the new location of the element that followed the last element erased by the function call, which is the list end if the operation erased the last element in the sequence.

Example
// erasing from list
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  unsigned int i;
  list<unsigned int> mylist;
  list<unsigned int>::iterator it1,it2;

  // set some values:
  for (i=1; i<10; i++) mylist.push_back(i*10);

                              // 10 20 30 40 50 60 70 80 90
  it1 = it2 = mylist.begin(); // ^^
  advance (it2,6);            // ^                 ^
  ++it1;                      //    ^              ^

  it1 = mylist.erase (it1);   // 10 30 40 50 60 70 80 90
                              //    ^           ^

  it2 = mylist.erase (it2);   // 10 30 40 50 60 80 90
                              //    ^           ^

  ++it1;                      //       ^        ^
  --it2;                      //       ^     ^

  mylist.erase (it1,it2);     // 10 30 60 80 90
                              //        ^

  cout << "mylist contains:";
  for (it1=mylist.begin(); it1!=mylist.end(); ++it1)
    cout << " " << *it1;
  cout << endl;

  return 0;
}
 
Output:
mylist contains: 10 30 60 80 90 

swap

void swap ( list<T,Allocator>& lst );  

Swap content

Exchanges the content of the vector by the content of lst, which is another list object containing elements of the same type. Sizes may differ.

After the call to this member function, the elements in this container are those which were in lst before the call, and the elements of lst are those which were in this. All iterators, references and pointers remain valid for the swapped objects.

Notice that a global algorithm function exists with this same name, swap, and the same behavior.


Parameters
lst 
Another list container of the same type as this whose content is swapped with that of this container. 

Return value
none

Example
// swap lists
#include <iostream>
#include <list>
using namespace std;

main ()
{
  list<int> first (3,100);   // three ints with a value of 100
  list<int> second (5,200);  // five ints with a value of 200
  list<int>::iterator it;

  first.swap(second);

  cout << "first contains:";
  for (it=first.begin(); it!=first.end(); it++) cout << " " << *it;

  cout << "\nsecond contains:";
  for (it=second.begin(); it!=second.end(); it++) cout << " " << *it;

  cout << endl;

  return 0;
}
 

Output:
first contains: 200 200 200 200 200 
second contains: 100 100 100  

clear

void clear ( );  

Clear content

All the elements in the list container are dropped: their destructors are called, and then they are removed from the list container, leaving it with a size of 0.


Parameters
none

Return value
none

Example
// clearing lists
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;
  list<int>::iterator it;

  mylist.push_back (100);
  mylist.push_back (200);
  mylist.push_back (300);

  cout << "mylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;

  mylist.clear();
  mylist.push_back (1101);
  mylist.push_back (2202);

  cout << "\nmylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}
 

Output:
mylist contains: 100 200 300
mylist contains: 1101 2202 

splice

void splice ( iterator position, list<T,Allocator>& x );
void splice ( iterator position, list<T,Allocator>& x, iterator i );
void splice ( iterator position, list<T,Allocator>& x, iterator first, iterator last );  

Move elements from list to list

Moves elements from list x into the list container at the specified position, effectively inserting the specified elements into the container and removing them from x.

This increases the container size by the amount of elements inserted, and reduces the size of x by the same amount ( whenever x is not the same as *this ).

The operation does not involve the construction or destruction of any element object and, except for the third version, it is performed in constant time.

The iterators that pointed to moved elements are no longer valid.


Parameters
position 
Position within the container where the elements of x are inserted.
iterator is a member type, defined as a bidirectional iterator. 
x 
A list object containing the same type of objects as this container.
This parameter may be *this if position points to an element not actually being spliced: for the first version, this is never the case, but for the other versions this is possible. 
i 
Iterator to an element in x. Only this single element is moved.
iterator is a member type, defined as a bidirectional iterator type. 
first,last 
Iterators specifying a range of elements in x. Moves the elements in the range [first,last) to position.
Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
iterator is a member type, defined as a bidirectional iterator type. 

Return value
none

Example
// splicing lists
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist1, mylist2;
  list<int>::iterator it;

  // set some initial values:
  for (int i=1; i<=4; i++)
     mylist1.push_back(i);      // mylist1: 1 2 3 4

  for (int i=1; i<=3; i++)
     mylist2.push_back(i*10);   // mylist2: 10 20 30

  it = mylist1.begin();
  ++it;                         // points to 2

  mylist1.splice (it, mylist2); // mylist1: 1 10 20 30 2 3 4
                                // mylist2 (empty)
                                // "it" still points to 2 (the 5th element)
                                          
  mylist2.splice (mylist2.begin(),mylist1, it);
                                // mylist1: 1 10 20 30 3 4
                                // mylist2: 2
                                // "it" is now invalid.
  it = mylist1.begin();
  advance(it,3);                // "it" points now to 30

  mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
                                // mylist1: 30 3 4 1 10 20

  cout << "mylist1 contains:";
  for (it=mylist1.begin(); it!=mylist1.end(); it++)
    cout << " " << *it;

  cout << "\nmylist2 contains:";
  for (it=mylist2.begin(); it!=mylist2.end(); it++)
    cout << " " << *it;
  cout << endl;

  return 0;
}
 
Output:
mylist1 contains: 30 3 4 1 10 20mylist2 contains: 2 

remove

void remove ( const T& value );  

Remove elements with specific value

Removes from the list all the elements with a specific value. This calls the destructor of these objects and reduces the list size by the amount of elements removed.

Unlike member function list::erase, which erases elements by their position (iterator), this function (list::remove) removes elements by their value.

A similar function, list::remove_if, exists, which allows for a condition other than a plain value comparison to be performed on each element in order to determine the elements to be removed.

Notice that a global algorithm function, remove, exists with a similar behavior but operating between two iterators.


Parameters
value 
Value of the elements to be removed.
T is the first class template parameter (the type of the elements stored in the list container). 

Return value
none

Example
// remove from list
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  int myints[]= {17,89,7,14};
  list<int> mylist (myints,myints+4);

  mylist.remove(89);

  cout << "mylist contains:";
  for (list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;
  cout << endl;

  return 0;
}
 

Output:
mylist contains: 17 7 14 

remove_if

template <class Predicate>
  void remove_if ( Predicate pred );  

Remove elements fulfilling condition

Removes from the list all the elements for which Predicate pred returns true. This calls the destructor of these objects and reduces the list size by the amount of elements removed.

Predicate pred can be implemented as any typed expression taking one argument of the same type as the list and returning a bool (this may either be a function pointer or an object whose class implements operator().

The function calls pred(*i) for each element (where i is an iterator to that element). Any of the elements in the list for which this returns true, is removed from the container.

Notice that a global algorithm function, remove_if, exists with a similar behavior but operating between two iterators.


Parameters
pred 
Unary predicate that, taking a value of the same type as those contained in the list object, returns true for those values to be removed from the container, and false for those remaining. 

Return value
none

Example
// list::remove_if
#include <iostream>
#include <list>
using namespace std;

// a predicate implemented as a function:
bool single_digit (const int& value) { return (value<10); }

// a predicate implemented as a class:
class is_odd
{
public:
  bool operator() (const int& value) {return (value%2)==1; }
};

int main ()
{
  int myints[]= {15,36,7,17,20,39,4,1};
  list<int> mylist (myints,myints+8);   // 15 36 7 17 20 39 4 1

  mylist.remove_if (single_digit);      // 15 36 17 20 39

  mylist.remove_if (is_odd());          // 36 20

  cout << "mylist contains:";
  for (list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;
  cout << endl;

  return 0;
}
 

Output:
mylist contains: 36 20 

unique

 void unique ( );
template <class BinaryPredicate>
  void unique ( BinaryPredicate binary_pred );  

Remove duplicate values

The first version, with no parameters, removes all but the first element from every consecutive group of equal elements in the list container.

Notice that an element is only removed from the list if it is equal to the element immediately preceding it. Thus, this function is specially useful for sorted lists.

For the second version, accepting a binary predicate, a specific comparison function to determine the "uniqueness" of an element can be specified. In fact, any behavior can be implemented (and not only a plain comparison), but notice that the function will call binary_pred(*i,*(i-1)) for all pairs of elements (where i is an iterator to an element) and remove i from the list if the predicate returns true.

The elements removed have their destructors called and their iterators and references become invalid.

A global algorithm function, unique, exists with a similar behavior but operating between two iterators.


Paramaters
BinaryPredicate 
Binary predicate that, taking two values of the same type than those contained in the list object, returns true to remove from the container the element passed as first argument, and false otherwise. 

Return value
none

Example
// list::unique
#include <iostream>
#include <cmath>
#include <list>
using namespace std;

// a binary predicate implemented as a function:
bool same_integral_part (double first, double second)
{ return ( int(first)==int(second) ); }

// a binary predicate implemented as a class:
class is_near
{
public:
  bool operator() (double first, double second)
  { return (fabs(first-second)<5.0); }
};

int main ()
{
  double mydoubles[]={ 12.15,  2.72, 73.0,  12.77,  3.14,
                       12.77, 73.35, 72.25, 15.3,  72.25 };
  list<double> mylist (mydoubles,mydoubles+10);
  
  mylist.sort();             //  2.72,  3.14, 12.15, 12.77, 12.77,
                             // 15.3,  72.25, 72.25, 73.0,  73.35

  mylist.unique();           //  2.72,  3.14, 12.15, 12.77
                             // 15.3,  72.25, 73.0,  73.35

  mylist.unique (same_integral_part);  //  2.72,  3.14, 12.15
                                       // 15.3,  72.25, 73.0

  mylist.unique (is_near());           //  2.72, 12.15, 72.25

  cout << "mylist contains:";
  for (list<double>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;
  cout << endl;

  return 0;
}
 

Output:
mylist contains: 2.72 12.15 72.25 

merge

 void merge ( list<T,Allocator>& x );
template <class Compare>
  void merge ( list<T,Allocator>& x, Compare comp );  

Merge sorted lists

Merges x into the list, inserting all the elements of x into the list object at their respective ordered positions. This empties x and increases the list size.

The second version (template function), has the same behavior, but takes a specific function to perform the comparison operation in charge of determining the insertion points. The comparison function has to perform weak strict ordering (which basically means the comparison operation has to be transitive and irreflexive).

The merging is performed using two iterators: one to iterate through x and another one to keep the insertion point in the list object; During the iteration of x, if the current element in x compares less than the element at the current insertion point in the list object, the element is removed from x and inserted into that location, otherwise the insertion point is advanced. This operation is repeated until either end is reached, in which moment the remaining elements of x (if any) are moved to the end of the list object and the function returns (this last operation is performed in constant time).

The entire operation does not involve the construction or destruction of any element object.

If no ordering is required, another option for merging lists is member function list::splice, which is faster.


Parameters
x 
A list object containing the same type of objects as this container. 
comp 
Comparison function that, taking two values of the same type than those contained in the list object, returns true if the first argument is less than the second, and false otherwise. 

Return value
none

Example
// list::merge
#include <iostream>
#include <list>
using namespace std;

// this compares equal two doubles if
//  their interger equivalents are equal
bool mycomparison (double first, double second)
{ return ( int(first)<int(second) ); }

int main ()
{
  list<double> first, second;

  first.push_back (3.1);
  first.push_back (2.2);
  first.push_back (2.9);

  second.push_back (3.7);
  second.push_back (7.1);
  second.push_back (1.4);

  first.sort();
  second.sort();

  first.merge(second);

  second.push_back (2.1);

  first.merge(second,mycomparison);

  cout << "first contains:";
  for (list<double>::iterator it=first.begin(); it!=first.end(); ++it)
    cout << " " << *it;
  cout << endl;

  return 0;
}
 

Output:
first contains: 1.4 2.2 2.9 2.1 3.1 3.7 7.1 

sort

 void sort ( );
template <class Compare>
  void sort ( Compare comp );  

Sort elements in container

Sorts the elements in the container from lower to higher. The sorting is performed by comparing the elements in the container in pairs using a sorting algorithm.

In the first version, taking no parameters, the comparisons are performed using the operator< between the elements being compared.

In the second version, the comparisons are perfomed using function comp, which performs weak strict ordering (this basically means the comparison operation has to be transitive and irreflexive).

The entire operation does not involve the construction or destruction of any element object.


Parameters
comp 
Comparison function that, taking two values of the same type than those contained in the list object, returns true if the first argument goes before the second argument in the specific order (i.e., if the first is less than the second), and false otherwise. 

Return value
none

Example
// list::sort
#include <iostream>
#include <list>
#include <string>
#include <cctype>
using namespace std;

// comparison, not case sensitive.
bool compare_nocase (string first, string second)
{
  unsigned int i=0;
  while ( (i<first.length()) && (i<second.length()) )
  {
    if (tolower(first[i])<tolower(second[i])) return true;
    ++i;
  }
  if (first.length()<second.length()) return true;
  else return false;
}

int main ()
{
  list<string> mylist;
  list<string>::iterator it;
  mylist.push_back ("one");
  mylist.push_back ("two");
  mylist.push_back ("Three");

  mylist.sort();

  cout << "mylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;
  cout << endl;

  mylist.sort(compare_nocase);

  cout << "mylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;
  cout << endl;

  return 0;
}
 

Output:
mylist contains: Three one twomylist contains: one Three two 

reverse

void reverse ( );  

Reverse the order of elements

Reverses the order of the elements in the list container.

All iterators and references to elements remain valid.


Parameters
none

Return value
none

Example
// reversing vector
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  list<int> mylist;
  list<int>::iterator it;

  for (int i=1; i<10; i++) mylist.push_back(i);

  mylist.reverse();

  cout << "mylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}
 

Output:
mylist contains: 9 8 7 6 5 4 3 2 1 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值