1 #include<iostream> 2 using namespace std; 3 #include "vector" //数组容器 4 #include "algorithm"//算法容器 5 6 void main11() 7 { 8 vector<int> v1; //1.v1是一个数组容器 9 v1.push_back(1); //将数据拷贝到容器中 10 v1.push_back(-1); 11 v1.push_back(3); 12 v1.push_back(5); 13 v1.push_back(3); 14 15 // 2.迭代器:相当于一个指针 16 for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) 17 { 18 cout << *it << " "; 19 } 20 21 //3算法 算法和迭代器进行无缝的链接 22 int num1 = count(v1.begin(), v1.end(), 3);// 这是统计数据的一个算法 23 24 cout << "num1 = " << num1 << endl; 25 26 } 27 28 29 int main() 30 { 31 32 33 main11(); 34 35 system("pause"); 36 return 0; 37 38 }
容器中装对象时:
#include<iostream> using namespace std; #include "vector" //数组容器 #include "algorithm"//算法容器 class Teacher { public: int age; char name[64]; public: void printF() { cout << "age : " << age << endl; } }; //容器中 装 元素 void main12() { Teacher t1, t2, t3; t1.age = 31; t2.age = 32; t3.age = 33; vector<Teacher> v1; //1.v1是一个数组容器 容器实现了数据类型和算法的有效分离 v1.push_back(t1); //将数据拷贝到容器中 v1.push_back(t2); v1.push_back(t3); // 2.迭代器:相当于一个指针 for (vector<Teacher>::iterator it = v1.begin(); it != v1.end(); it++) { cout << it->age << " "; } //3算法 算法和迭代器进行无缝的链接 //int num1 = count(v1.begin(), v1.end(), 3);// 这是统计数据的一个算法 //cout << "num1 = " << num1 << endl; } int main() { main12(); system("pause"); return 0; }
容器中装指针时:
#include<iostream> using namespace std; #include "vector" //数组容器 #include "algorithm"//算法容器 class Teacher { public: int age; char name[64]; public: void printF() { cout << "age : " << age << endl; } }; //容器中 装 元素 void main13() { 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; //1.v1是一个数组容器 容器实现了数据类型和算法的有效分离 v1.push_back(p1); //把t1,t2,t3内存首地址放入到了容器 v1.push_back(p2); v1.push_back(p3); // 2.迭代器:相当于一个指针 for (vector<Teacher *>::iterator it = v1.begin(); it != v1.end(); it++) { cout << (*it)->age << endl;//指针指向age } //3算法 算法和迭代器进行无缝的链接 //int num1 = count(v1.begin(), v1.end(), 3);// 这是统计数据的一个算法 //cout << "num1 = " << num1 << endl; } int main() { main13(); system("pause"); return 0; }