Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) std::list

 

std::list is a type of container like std::vector. Use std::vector by default [1].

 

std::list is suitable for constant-time random-access insertion and deletion at the cost of linear-time read and write.

 

#include <iterator>
#include <iostream>
#include <list>

int main()
{
  std::list<int> my_list;
  //Add a two at the end
  my_list.push_back(2);
  //Add a zero at the beginning
  my_list.push_front(0);
  //Obtain an iterator to a position in between
  std::list<int>::iterator my_iterator = my_list.begin();
  ++my_iterator;
  //Insert a one in between
  my_list.insert(my_iterator,1);
  //Display the list
  std::copy(my_list.begin(),my_list.end(),
    std::ostream_iterator<int>(std::cout,"\n"));
}

 

Screen output:

 

0
1
2

 

 

 

 

 

References

 

  1. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Chapter 76: 'Use vector by default. Otherwise, choose an appropriate container'.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict