c++(vector容器 和幾種常用的迭代器遍歷方法)
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
//迭代器 遍歷功能 用指針理解
//普通指針也算是一種迭代器
template<class T>
void printFun(T &arr,int size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i]<<" ";
}
cout << endl;
}
void test01()
{
int array[5] = { 1,3,5,6,8 };;
printFun(array,5);
}
void myPrint(int v) {
cout << v << endl;
}
void test02()
{
//聲明容器
vector<int> v; //聲明一個容器 這個容器中存放着int類型的數據
v.push_back(10);
v.push_back(11);
v.push_back(12);
v.push_back(13);
//便利容器中的數據
//利用迭代器
/*No.1
vector<int>::iterator itB = v.begin();
vector<int>::iterator itE = v.end();
while (itB != itE)
{
cout << *itB<< endl;
itB++;
}
*/
/*No.2
for (vector<int>::iterator itB = v.begin(); itB != v.end(); itB++)
cout << *itB << endl;
for (auto itB = v.begin(); itB != v.end(); ++itB)
{
cout << *itB << endl;;
}
*/
/*No.3
for_each(v.begin(), v.end(), myPrint);
void myPrint(int v) {
cout << v << endl;
}
*/
}
class Person
{
public:
Person(string name,int age):m_name(name),m_age(age){}
string m_name;
int m_age;
};
void test03()
{
vector<Person> v1;
Person p1("老王", 10);
Person p2("老李", 11);
Person p3("老劉", 12);
Person p4("老趙", 13);
Person p5("老猴", 14);
v1.push_back(p1);
v1.push_back(p2);
v1.push_back(p3);
v1.push_back(p4);
v1.push_back(p5);
for (vector<Person>::iterator itB = v1.begin(); itB != v1.end(); ++itB)
{
cout << "姓名: " << (*itB).m_name << " 年齡: " << itB->m_age << endl;
}
}
void test04()
{
vector<Person *> v1;
Person p1("老王", 10);
Person p2("老李", 11);
Person p3("老劉", 12);
Person p4("老趙", 13);
Person p5("老猴", 14);
v1.push_back(&p1);
v1.push_back(&p2);
v1.push_back(&p3);
v1.push_back(&p4);
v1.push_back(&p5);
for (auto &a : v1)
{
cout << a->m_name << " " << a->m_age << endl;
}
/*
for (auto itB = v1.begin(); itB != v1.end(); ++itB)
{
cout << (*itB)->m_name << " " << (*itB)->m_age << endl;
}
*/
/*
for (vector<Person *>::iterator itB = v1.begin(); itB != v1.end(); itB++)
{
cout << (*itB)->m_name << " age " << (*itB)->m_age << endl;
}
*/
}