vector
1.vector存放内置数据类型
容器:vector
算法:for_each
迭代器:vector<int>::iterator
#include<iostream>
#include<vector>
#include<algorithm>//标准算法的头文件
using namespace std;
//vector 容器存放内置数据类型
void myprint(int val)
{
cout<<val<<endl;
}
void test()
{
//创建
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
vector<int>::iterator itBegin=v.begin();
vector<int>::iterator itEnd=v.end();
/*第一种遍历方式
while(itBegin!=itEnd)
{
cout<<* iterator<<endl;
itBegin++;
}*/
/*
第二种遍历方式
for(vector<int>::iterator it=v.begin();it!v.end();it++)
{
cout<<*it<<endl;
}
*/
//第三种遍历方式 利用STL提供的算法
for_each(v.begin(),v.end(),myprint);//回调
}
int main()
{
test();
return 0;
}
2.vector存放自定义数据类型
#include<iostream>标签:iterator,int,Vetcor1,back,Person,vector,push From: https://www.cnblogs.com/daitu66/p/17023287.html
#include<vector>
#include<string>
using namespace std;
class Person
{
public:
Person(string name,int age)
{
this->m_name=name;
this->m_Age=age;
}
string m_name;
int m_Age;
};
void test01()
{
vector<Person>v;
//添加数据
Person p1("aaa",10);
Person p2("bbb",20);
Person p3("ccc",30);
Person p4("ddd",40);
Person p5("eee",50);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
//遍历容器中数据
for(vector<Person>::iterator it=v.begin();it!=v.end();it++)
{
cout<<"姓名"<<(*it).m_name<<"年龄"<<(*it).m_Age<<endl;
//cout<<"姓名"<<it->m_name<<"年龄"<<it->m_Age<<endl;
}
}
void test02()
{
vector<Person*>v;
//添加数据
Person p1("aaa",10);
Person p2("bbb",20);
Person p3("ccc",30);
Person p4("ddd",40);
Person p5("eee",50);
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
v.push_back(&p5);
for(vector<Person*>::iterator it=v.begin();it!=v.end();it++)
{
cout<<"姓名"<<(*it)->m_name<<"年龄"<<(*it)->m_Age<<endl;
//cout<<"姓名"<<it->m_name<<"年龄"<<it->m_Age<<endl;
}
}
int main()
{
//test01();
test02();
system("pause");
}