vector优势:1.随机访问 2.在尾部插入删除元素
#include<iostream>
#include<vector>
using namespace std;
void Print(vector<int>& vec)
{
for(int i = 0; i < vec.size(); ++i)cout<<' '<<vec[i];
cout<<endl;
}
int main()
{
vector<int> first;
vector<int> second(4, 1000);
vector<int> third(second.begin() + 2, second.end());
vector<int> forth(third);
vector<int>::iterator it;
int val[] = {1,2,3,4};
vector<int> fifth(val, val + sizeof(val) / sizeof(val[0]));
cout<<"First:";
Print(first);
cout<<"Second:";
Print(second);
cout<<"Third:";
Print(third);
cout<<"Forth:";
Print(forth);
cout<<"Fifth:";
Print(fifth);
first.swap(fifth);
cout<<"First:";
Print(first);
first.push_back(12);
cout<<"First:";
Print(first);
it = first.begin() + 2;
first.erase(it,first.end());
cout<<"First:";
Print(first);
it = first.begin();
first.insert(it,100);
cout<<"First:";
Print(first);
system("pause");
return 0;
}
结果:
Deque操作代码类似。
优势:比之Vector在头部插入删除元素也有很高效率。也支持迭代器随机访问。不过元素在内存中不连续。
List操作基本相同不过多了一些功能
优势:高效遍历元素,常量时间插入删除任意位置元素。
#include<iostream>
#include<list>
using namespace std;
void Print(list<int>& ls)
{
list<int>::iterator it = ls.begin();
for(; it != ls.end(); ++it)cout<<' '<<*it;
cout<<endl;
}
void Print(list<double>& ls)
{
list<double>::iterator it = ls.begin();
for(; it != ls.end(); ++it)cout<<' '<<*it;
cout<<endl;
}
int main()
{
list<int> first;
list<int> second(4, 1000);
list<int>::iterator it;
double first_val[] = {1.0,3.0,2.0,4.0};
list<double> third(first_val, first_val + sizeof(first_val) / sizeof(first_val[0]));
double sencond_val[] = {1.1,4.3,1.4,2.9};
list<double> fourth(sencond_val, sencond_val + sizeof(sencond_val)/sizeof(sencond_val[0]));
it = first.begin();
first.insert(it,100);
cout<<"First:";
Print(first);
it = first.begin();
first.splice(it,second);//splice四个参数,第一个参数是插入的位置,第二个是插入源,第三四个参数指定范围
cout<<"First:";
Print(first);
first.remove(100);
cout<<"First:";
Print(first);
third.sort();
fourth.sort();
cout<<"Third:";
Print(third);
cout<<"Fourth:";
Print(fourth);
third.merge(fourth);
cout<<"Third:";
Print(third);
system("pause");
return 0;
}
结果:
splice在代码中已经说明,merge函数合并两个list而且是按照从小到大的顺序,merge有另一个版本包含两个参数,另一个是一个
返回bool类型的函数,说明了比较规则。用法相同。另外一些函数使用比较简单。
该类笔记均参考:
www.cplusplus.com