2.5 .1. vector 存放内置数据类型
容器: vector
算法: for_each
迭代器: vector<int> ::iterator
示例:
#include<iostream>
#include<vector>
using namespace std;
void myprint(int val)
{
cout<<val<<endl;
}
void test()
{
vector<int>v;//创建一个名为v的vector容器
v.push_back(10);//向容器尾部插入 10
v.push_back(20);// 向容器尾部插入 20
vector<int>::iterator itbegin=v.begin(); // 通过迭代器访问容器内的数据 起始迭代器 第一个数据
vector<int>::iterator itend = v.end(); // 结束迭代器 指向容器容器最后一个元素的后一个位置
while(itbegin!=itend) //第一种遍历方式
{
cout<<*itbegin<<endl;
itbegin++;
}
for(vector<int>::iterator it=v.begin();it!=v.end();it++) //第二种遍历方式
{
cout<<*it<<endl;
}
for_each(v.begin(),v.end(),myprint); // 第三种遍历方式
}
int main()
{
test();
}
2.5.2 vector 存放自定义数据类型
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class person
{
public:
person(string name,int age)
{
m_name=name;
m_age=age;
}
string m_name;
int m_age;
};
void test()
{
vector<person>v;
person p1("aaa",10);
person p2("bbb",20);
v.push_back(p1);// 向容器中添加数据
v.push_back(p2);
for(vector<person>::iterator it=v.begin(),it!=v.end(),it++) //遍历容器中的数据
{
cout<<(*it).m_name<<endl;
cout<<(*it).m_age<<endl;
cout<<it->m_name<<endl;
cout<<it->age<<endl;
}
}
//存放自定义数据类型的指针
void test01()
{
vector<person*>v;
person p1("aaa",10);
person p2("bbb",20);
v.push_back(&p1);//向容器中添加数据
v.push_back(&p2);
for(vector<person*>::iterator it=v.begin(),it!=v.end(),it++) //遍历容器中的数据
{
cout<<(*it)->m_name<<endl;
cout<<(*it)->age<<endl;
}
}
int main()
{
test();
test01();
}