雙向鏈表list V.S. 鏈表forward_list
共性
都是便于插入糠悯、刪除帮坚,但是查找需要O(n)的時(shí)間妻往。比較適合在排序算法里
差別
list 雙向鏈表,
forward_list 單向鏈表试和,更小,更高效
使用方式
construct 新建阅悍,空的好渠,復(fù)制型的,從列表初始化型的
// constructing lists
#include <iostream>
#include <list>
int main()
{
// constructors used in the same order as described above:
std::list<int> first; // empty list of ints
std::list<int> second(4, 100); // four ints with value 100
std::list<int> third(second.begin(), second.end()); // iterating through second
std::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 };
std::list<int> fifth(myints, myints + sizeof(myints) / sizeof(int));
std::cout << "The contents of fifth are: ";
for (std::list<int>::iterator it = fifth.begin(); it != fifth.end(); it++)
std::cout << *it << ' ';
std::cout << '\n';
return 0;
}
list<int> list_(3) 表示建立三個(gè)0 的list
.erase()的用法
.erase(list<int>::iterator it1) 一個(gè)參數(shù)時(shí)节视,是刪除該指針現(xiàn)在指向的元素
.erase(list<int>::iterator it1拳锚,it2) 兩個(gè)參數(shù)時(shí),是刪除之陣中中間段寻行,左閉右開霍掺,[ it1, it2)
【注】advance(it2, 5) 指 指針 往前移5位 即 it2 += 5;
#include <iostream>
#include <list>
int main()
{
std::list<int> mylist;
std::list<int>::iterator it1, it2;
// set some values:
for (int 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
// ^
std::cout << "mylist contains:";
for (it1 = mylist.begin(); it1 != mylist.end(); ++it1)
std::cout << ' ' << *it1;
std::cout << '\n';
return 0;
}