1、vector存放内置数据类型
#include<iostream>
using namespace std;
#include<string>
#include<vector>
#include<algorithm>
void myPrint(int val)
{
cout << val << endl;
}
void test01()
{
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();
for_each(v.begin(), v.end(), myPrint);
}
int main()
{
test01();
system("pause");
return 0;
}
2、容器存放自定义数据类型
#include<iostream>
using namespace std;
#include<string>
#include<vector>
#include<algorithm>
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);
v.push_back(p1);
v.push_back(p2);
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);
v.push_back(&p1);
v.push_back(&p2);
for (vector<Person*>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名:" << (*it)->m_Name << "年龄:" << (*it)->m_Age << endl;
}
}
int main()
{
test02();
system("pause");
return 0;
}
3、容器嵌套容器
#include<iostream>
using namespace std;
#include<string>
#include<vector>
#include<algorithm>
void test01()
{
vector<vector<int>>v;
vector<int> v1;
vector<int> v2;
vector<int> v3;
vector<int> v4;
for (int i = 0; i < 3; i++)
{
v1.push_back(i + 1);
v2.push_back(i + 2);
v3.push_back(i + 3);
v4.push_back(i + 4);
}
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
v.push_back(v4);
for (vector<vector<int>>::iterator it = v.begin(); it != v.end(); it++)
{
for (vector<int>::iterator vit = (*it).begin(); vit != (*it).end(); vit++)
{
cout << *vit << " ";
}
cout << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}