list
双向列表,链式存储
1 生成构造
// 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::list<int> first (3); // list of 3 zero-initialized ints
std::list<int> second (5); // list of 5 zero-initialized ints
second = first;//second size is 3
return 0;
}
2 操作
2.1 大小和容量
/*
* size max_size empty resize
*/
#include <iostream>
#include <list>
int main ()
{
//capacity
std::list<int> mylist(5,1);
mylist.size(); //size is 5
mylist.max_size();
mylist.resize(10);
mylist.empty(); //0
return 0;
}
2.2 比较
2.3 find
2.4 截取部分
2.5 增,插,删,改
/*
* modify element
* assign pop_back pop_front
* push_back push_front insert
* erase clear swap
*/
#include <iostream>
#include <list>
int main ()
{
//modify elements
std::list<int> mylist(5,1);
mylist.assign(3,2); //mylist={2,2,2}
mylist.pop_back();
mylist.pop_front(); //mylist={2}
mylist.push_back(1);
mylist.push_front(3); //mylist={3,2,1}
mylist.insert(mylist.cbegin(),2); //mylist={2,3,2,1}
int ints[]={9,5,2,7};
mylist.insert(mylist.cbegin(),ints,ints+4); //mylist={9,5,2,7,2,3,2,1}
mylist.erase(mylist.begin()); //because is 链式存储,位置还真不好确定,因此remove出现了
mylist.remove(2); //delete element of value is 2
mylist.clear();
std::list<int> mylist2(3,1);
mylist.swap(mylist2);
for(auto it=mylist.cbegin();it!=mylist.cend();it++)
std::cout<<*it<<' ';
return 0;
}
2.6元素存取
/*
* element access
* back font
*/
#include <iostream>
#include <list>
int main ()
{
//elemnet access
std::list<int> mylist(5,1);
mylist.back(); //1
mylist.front(); //1
return 0;
}
2.7其他
// list::merge
//unique去重复
//sort()排序
//reverse()倒置list
#include <iostream>
#include <list>
// compare only integral part:只是考虑整数部分,因此插入位置不是你想的那样按大小排序
bool mycomparison (double first, double second)
{ return ( int(first)<int(second) ); }
int main ()
{
std::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);
// ( now second is empty)
second.push_back (2.1);
first.merge(second,mycomparison);
std::cout << "first contains:";
for (std::list<double>::iterator it=first.begin(); it!=first.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}