C++标准模板库代码实现vector,list,map
#include
#include <stdlib.h>
#include
#include
#include
int main()
{
/**
*vector
**/
//定义向量
vector vec;
//从向量尾部插入数据
vec.push_back(3);
vec.push_back(4);
vec.push_back(6);
//遍历
cout<<“所有元素为:”<<endl;
for(unsigned int i=0;i<vec.size();i++){
cout<<vec[i]<<endl;
}
//打印出向量中数据的个数
cout<<“vec中数据数:”<<vec.size()<<endl;
//去除尾部数据
vec.pop_back();
cout<<“去除尾部的一个数据后:”<<vec.size()<<endl;
//迭代器是与类相关的
vector::iterator itor=vec.begin();//迭代器iterator拿到第一个元素
cout<<“第一个数据为:”<<*itor<<endl;
for(;itor!=vec.end();itor++){//vec.end()为最后一个元素的后面一个位置
cout<<*itor<<endl;
}
//front()方法
cout<<vec.front()<<endl;
//back()方法
cout<<vec.back()<<endl;
/**
*list
**/
list<int>list1;
list1.push_back(4);
list1.push_back(7);
list1.push_back(10);
/*for(unsigned int i=0;i<list.size();i++){
cout<<list1[i]<<endl;
}*/
list<int>::iterator itor1=list1.begin();
for(;itor1!=list1.end();itor1++){
cout<<*itor1<<endl;
}
/**
*map
**/
map<int,string> m;
pair<int,string> p1(3,"hello");
pair<int,string> p2(6,"world");
pair<int,string> p3(8,"BeiJing");
m.insert(p1);
m.insert(p2);
m.insert(p3);
cout<<m[3]<<endl;
cout<<m[6]<<endl;
map<int,string>::iterator itor2=m.begin();
for(;itor2!=m.end();itor2++){
cout<<itor2->first<<endl;
cout<<itor2->second<<endl;
cout<<endl;
}
map<string,string> m1;
pair<string,string> pa1("H","hello");
pair<string,string> pa2("W","world");
pair<string,string> pa3("B","BeiJing");
m1.insert(pa1);
m1.insert(pa2);
m1.insert(pa3);
cout<<m1["H"]<<endl;
cout<<m1["B"]<<endl;
map<string,string>::iterator itor3=m1.begin();
for(;itor3!=m1.end();itor3++){
cout<<itor3->first<<endl;
cout<<itor3->second<<endl;
cout<<endl;
}
return 0;
}