STL中最常用的容器为vector,可以理解为数组,通过该容器,初识STL
vector存放内置数据类型
容器:vector
算法:for_each
迭代器:vector
#include
using namespace std;
#include
#include//标准算法头文件
void myPrint(int val)
{
cout }
int main()
{
//创建一个vector容器,数组
vectorv;
//向容器中插入数据
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
//通过迭代器访问容器中的数据
//起始迭代器,指向容器中第一个元素
vector::iterator itBegin = v.begin();
//结束迭代器,指向容器中最后一个元素的下一个位置
vector::iterator itEnd = v.end();
//第一种遍历方式
while (itBegin != itEnd)
{
cout itBegin++;
}
//第二种遍历
for (vector::iterator it = v.begin(); it != v.end(); it++)
{
cout }
//第三种遍历,利用STL提供的遍历算法
for_each(v.begin(), v.end(), myPrint);
return 0;
}
vector存放自定义数据类型
vector
中*it
是Person*
#include
using namespace std;
#include
#include
#include
class Person
{
public:
string m_name;
int m_age;
Person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
};
int main()
{
vectorv;
Person p1("A", 1);
Person p2("B", 2);
Person p3("C", 3);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
for (vector::iterator it = v.begin(); it != v.end(); it++)
{
cout }
return 0;
}
vectorv;
Person p1("A", 1);
Person p2("B", 2);
Person p3("C", 3);
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
for (vector::iterator it = v.begin(); it != v.end(); it++)
{
cout }
vector容器嵌套容器
#include
using namespace std;
#include
#include
#include
class Person
{
public:
string m_name;
int m_age;
Person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
};
int main()
{
vector> v;
vectorv1;
vectorv2;
vectorv3;
vectorv4;
//向小容器中添加数据
for (int i = 0; i {
v1.push_back(i);
v2.push_back(i + 1);
v3.push_back(i + 2);
v4.push_back(i + 3);
}
//将小容器添加到大容器中
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
v.push_back(v4);
//通过大容器,把所有数据遍历一遍
for (vector>::iterator it = v.begin(); it != v.end(); it++)
{
for (vector::iterator vit = (*it).begin(); vit != (*it).end(); vit++)
{
cout }
cout }
return 0;
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net