Vector容器的简单应用
Part1:
1.数据存入;
2.迭代器访问容器中的数据
3.遍历方式获得数据
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
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 << *itBegin << endl;
itBegin++;
}*/
//遍历访问2
for (vector<int>::iterator itBegin=v.begin(); itBegin!=v.end(); itBegin++)
{
cout << *itBegin << endl;
}
}
void show(int value)
{
cout << value << endl;
}
void test1()
{
vector<int> v;
v.push_back(100);
v.push_back(200);
v.push_back(300);
v.push_back(400);
//通过迭代器访问数据中的容器
vector<int>::iterator itBegin = v.begin();
vector<int>::iterator itEnd = v.end();
for_each(v.begin(), v.end(),show);
}
int main()
{
test(); test1();
system("pause");
return 0;
}
通过STL中的for_each时,需要对包含头文件algorithm,同时for_each的使用需要配合其他函数
Part2:
1.容器–访问自定义数据类型
2.容器–指针方式访问
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
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 test()
{
Person p1("aaa", 10); Person p2("bbb", 20); Person p3("ccc", 30); Person p4("ddd", 40); Person p5("eee", 50);
vector<Person>v;
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
vector<Person>::iterator itBegin = v.begin();
vector<Person>::iterator itEnd = v.end();
for (vector<Person>::iterator itBegin = v.begin(); itBegin !=itEnd; itBegin++)
{
cout << "姓名:" << (*itBegin).m_name << "年龄:" <<(*itBegin).m_age<< endl;
cout << "姓名:" << itBegin->m_name << "年龄:" << itBegin->m_age << endl;
}
}
//容器存放自定义数据类型 指针
void test1()
{
Person p1("aaa", 10); Person p2("bbb", 20); Person p3("ccc", 30); Person p4("ddd", 40); Person p5("eee", 50);
vector<Person*>v;
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
v.push_back(&p5);
vector<Person*>::iterator itBegin = v.begin();
vector<Person*>::iterator itEnd = v.end();
for (vector<Person*>::iterator itBegin = v.begin(); itBegin != itEnd; itBegin++)
{
//cout << "姓名:" << (*itBegin).m_name << "年龄:" << (*itBegin).m_age << endl;
cout << "姓名:" << (*itBegin)->m_name << "年龄:" << (*itBegin)->m_age << endl;
}
}
int main()
{
test(); test1();
system("pause");
return 0;
}