初识容器 算法 迭代器
问题:
stl概念,好处,包含什么?
哪6大组件
vector容器
自定义数据类型迭代器输入,输出方法
- vector<数据类型>::iterator 可将迭代器视为指针
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
class person {
public:
person(string name, int age) {
this->name = name;
this->age = age;
}
public:
string name;
int age;
};
void MyPrint(person p)
{
cout << "name:" << p.name << endl;
cout << "age:" << p.age << endl;
}
//1.内置函数法
void outputfunc1(vector<person>v){
cout << "outputfunc1**********" << endl;
for_each(v.begin(), v.end(), MyPrint);
cout << v.begin()->name << endl;
cout << v.begin()->age << endl;
}
//2.迭代器指针法 -> 法for循环递增指针位置
void outputfunc2(vector<person>v) {
cout << "outputfunc2*********" << endl;
for (vector<person>::iterator it = v.begin(); it != v.end(); it++) {
cout << "name:" << it->name << endl;
cout << "age:" << it->age << endl;
}
}
//2.迭代器指针法 * 法
void outputfunc3(vector<person>v){
cout << "outputfunc3*********" << endl;
for (vector<person>::iterator it=v.begin(); it != v.end(); it++) {
cout<<"---name:"<<(*it) .name << endl;
cout<<"---age:"<< (*it).age <<endl;//(*it).age和*it.age不同,会误认为指向it.age
}
}
//2.迭代器指针法 常规while循环
void outputfunc4(vector<person>v) {
cout << "outputfunc4*********" << endl;
vector<person>::iterator pbegin = v.begin();
// vector<person>::iterator pend = v.end();
// while (pbegin != pend){……}
while (pbegin != v.end() ){
cout <<"name:" << pbegin->name << endl;
cout << "age:" << pbegin->age << endl;
pbegin++;
}
}
void test01() {
vector<person>v;//init vector
person p1("小米", 6);//create objects
person p2("小红", 18);
person p3("小江", 15);
v.push_back(p1);//input elements
v.push_back(p2);
v.push_back(p3);
outputfunc1(v);
outputfunc2(v);
outputfunc3(v);
outputfunc4(v);
}
int main() {
test01();
system("pause");
return 0;
}
本文来自博客园,作者:_JunJun,转载请注明原文链接:https://www.cnblogs.com/--ah/p/15975326.html