List内部结构完全不同于array, vector, deque。
它提供了两个pointer,指向第一个和最后一个元素。
不支持随机访问元素,因此要访问第n个元素必须爬过n - 1个元素。
在任何位置上执行元素的插入和删除操作都很快。
因此会有一些属于list的特殊类型操作,比如merge, splice等。
ListTest.cpp
#include <iostream>
#include <deque>
#include <list>
#include <iostream>
#include <algorithm>
#include <iterator>
#include "ListTest.h" using namespace std; void ListTest::printLists(const list<int>& l1, const list<int>& l2)
{
cout << "list1: ";
copy(l1.cbegin(), l1.cend(), ostream_iterator<int>(cout, " "));
cout << endl << "list2: ";
copy(l2.cbegin(), l2.cend(), ostream_iterator<int>(cout, " "));
cout << endl << endl;
} void ListTest::simpleOperation()
{
// create two empty lists
list<int> list1, list2; // fill both lists with elements
for (int i = ; i<; ++i) {
list1.push_back(i);
list2.push_front(i);
}
printLists(list1, list2); // insert all elements of list1 before the first element with value 3 of list2
// - find() returns an iterator to the first element with value 3
list2.splice(find(list2.begin(), list2.end(), // destination position
),
list1); // source list
printLists(list1, list2); // move first element of list2 to the end
list2.splice(list2.end(), // destination position
list2, // source list
list2.begin()); // source position
printLists(list1, list2); // sort second list, assign to list1 and remove duplicates
list2.sort();
list1 = list2;
list2.unique();
printLists(list1, list2); // merge both sorted lists into the first list
list1.merge(list2);
printLists(list1, list2); // remove all even elements
list1.remove_if([](int i) {
return i % == ;
});
printLists(list1, list2);
} void ListTest::run()
{
printStart("simpleOperation()");
simpleOperation();
printEnd("simpleOperation()");
}
运行结果:
---------------- simpleOperation(): Run Start ----------------
list1: 0 1 2 3 4 5
list2: 5 4 3 2 1 0
list1:
list2: 5 4 0 1 2 3 4 5 3 2 1 0
list1:
list2: 4 0 1 2 3 4 5 3 2 1 0 5
list1: 0 0 1 1 2 2 3 3 4 4 5 5
list2: 0 1 2 3 4 5
list1: 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
list2:
list1: 1 1 1 3 3 3 5 5 5
list2:
---------------- simpleOperation(): Run End ----------------