我常用的STL(标准模板库) vector,map:
vector:
#include <iostream>
#include <vector>
#include <map>
#include <algorithm> //包含着 std::Find()函数的实现
using namespace std;
#define MAX_SIZE 5
void main()
{
vector<int> vInt;//初始化一个整形的向量 初始都为空
vInt.clear();
for (int n = 0; n < MAX_SIZE; n++)
vInt.push_back(n);//在向量尾部依次插入0 到4
vector<int>::iterator itr = vInt.begin();//定义一个向量的迭代器 使它指向向量的头部
for (; itr != vInt.end();++itr)//向量的头部使有效值 而尾部不是有效值的,当迭代器没有指到尾部时 就一直的向下遍历
cout<<(*itr)<<endl;//输入迭代器所指的值,迭代器是类似于指针
vInt.pop_back();//在尾部删除一个元素
for (int n = 0; n < vInt.size(); n++)
cout<<vInt.at(n)<<endl;//.at()方法也是可以读取向量中的元素的
vector<int>::iterator itrFind = std::find(vInt.begin(),vInt.end(),2);//通过调用find函数找到指定值的迭代指针
if (itrFind != vInt.end())//判断是否找到了一个有效值
vInt.erase(itrFind);//用erase方法删除该迭代指针
for (int n = 0; n < vInt.size(); n++)
cout<<vInt[n]<<endl;//也可用[]去向量的值
vInt.resize(5,9);//将vInt的size扩展为5,新扩展的值初始为9,若5比原来的size小的话 那就保留前5个数值不变。
itr = vInt.begin();
for (; itr != vInt.end();++itr)
cout<<(*itr)<<endl;
cout<<vInt.size()<<endl;
vInt.assign(2,7);//将vInt的size设置为2 并初始化为7
itr = vInt.begin();
for (; itr != vInt.end();++itr)
cout<<(*itr)<<endl;
cout<<vInt.size()<<endl;
getchar();
}
map:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
#define MAX_SIZE 5
void main()
{
map<int,string> mapStr;//创建map
mapStr[0] = "One";//用数组方式初始化
mapStr.insert(pair<int,string>(1,"Two"));//用insert pair值初始化
mapStr.insert(map<int,string>::value_type(2,"Three"));//用insert value_type初始化
map<int,string>::iterator itr = mapStr.begin(),itr_end = mapStr.end();//前序遍历
for (;itr!= itr_end;++itr)
cout<<(*itr).first <<" "<<(*itr).second.c_str()<<endl;
map<int,string>::reverse_iterator Ritr = mapStr.rbegin(),Ritr_end = mapStr.rend();//后续遍历
for (;Ritr!=Ritr_end;++Ritr)
cout<<(*Ritr).first <<" "<<(*Ritr).second.c_str()<<endl;
getchar();
}