c++(vector容器 和几种常用的迭代器遍历方法)

2021/4/27 14:55:19

本文主要是介绍c++(vector容器 和几种常用的迭代器遍历方法),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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;
	}
	*/
}


这篇关于c++(vector容器 和几种常用的迭代器遍历方法)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程