#include<iostream>
using namespace std;
#include"vector"
#include"algorithm"
//1:容器中装基础类型变量
void f1()
{
vector<int> v1; //容器, 把你的元素copy到容器中
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
//迭代器,类似于一个指针 有多种分类
for (vector <int>::iterator it = v1.begin(); it != v1.end(); it++)
{
cout << *it << " ";
}
//算法 算法和迭代器进行无缝的连接
int numl = count (v1.begin(), v1.end(), 3); //计算3的个数
cout << "numl:" << numl << endl;
}
class Teacher
{
public:
int age;
char name[64];
public:
void prinT()
{
cout << "age:" << age << endl;
}
};
//2:容器中装自己定义的类
void f2()
{
Teacher t1, t2, t3;
t1.age = 31;
t2.age = 32;
t3.age = 33;
vector<Teacher> v1; //容器, 把你的元素copy到容器中
v1.push_back(t1); //容器实现了数据类型和算法的有效分离
v1.push_back(t2);
v1.push_back(t3);
//迭代器,相当于一个指针 有多种分类
for (vector <Teacher>::iterator it = v1.begin(); it != v1.end(); it++)
{
cout << it->age << " ";
}
/* //算法 算法和迭代器进行无缝的连接
int numl = count (v1.begin(), v1.end(), 3); //计算3的个数
cout << "numl:" << numl << endl;
*/
}
//2:容器中装指针
void f3()
{
Teacher t1, t2, t3;
t1.age = 31;
t2.age = 32;
t3.age = 33;
Teacher *p1, *p2, *p3;
p1 = &t1;
p2 = &t2;
p3 = &t3;
vector<Teacher *> v1; //容器, 把你的元素copy到容器中
v1.push_back(p1); //容器实现了数据类型和算法的有效分离
v1.push_back(p2);
v1.push_back(p3);
//迭代器,相当于一个指针 有多种分类
for (vector <Teacher *>::iterator it = v1.begin(); it != v1.end(); it++)
{
cout << (**it).age << " ";
}
/* //算法 算法和迭代器进行无缝的连接
int numl = count (v1.begin(), v1.end(), 3); //计算3的个数
cout << "numl:" << numl << endl;
*/
}
int main()
{
f3();
return 0;
}
STL容器算法迭代器入门
最新推荐文章于 2024-09-27 00:00:00 发布