1. vector存放内置数据类型
容器: vector
算法: for_each
迭代器: vector<int>::iterator
#include<vector> #include<algorithm> #include<iostream> using namespace std; void print(int val) { cout << val << endl; } void test() { vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); v.push_back(40); v.push_back(50); v.push_back(60); vector<int>::iterator p_Begin = v.begin(); vector<int>::iterator p_End = v.end(); while (p_Begin != p_End) { cout << *p_Begin << endl; p_Begin++; } cout << endl; for(vector<int>::iterator t = v.begin(); t != v.end(); t++) { cout << *t << endl; } cout << endl; for_each(v.begin(), v.end(), print); } int main() { test(); return 0; }
2.Vector存放自定义数据类型(定义类)
#include<vector> #include<algorithm> #include<iostream> #include<string> using namespace std; class person { public: person(string name, int age) { m_name = name; m_age = age; } public: string m_name; int m_age; }; void test() { vector<person> v; person p1("aaa", 10); person p2("bbb", 20); person p3("ccc", 30); person p4("ddd", 40); person p5("eee", 50); v.push_back(p1); v.push_back(p2); v.push_back(p3); v.push_back(p4); v.push_back(p5); for (vector<person>::iterator it = v.begin(); it != v.end(); it++) { cout <<"name is"<< (*it).m_name <<"age is" <<(*it).m_age<< endl; } } int main() { test(); return 0; }
指针型存放数据
#include<vector> #include<algorithm> #include<iostream> #include<string> using namespace std; class person { public: person(string name, int age) { m_name = name; m_age = age; } public: string m_name; int m_age; }; void test() { vector<person *> v; person p1("aaa", 10); person p2("bbb", 20); person p3("ccc", 30); person p4("ddd", 40); person p5("eee", 50); v.push_back(&p1); v.push_back(&p2); v.push_back(&p3); v.push_back(&p4); v.push_back(&p5); for (vector<person *>::iterator it = v.begin(); it != v.end(); it++) { person* p = (*it); cout <<"name is"<< (*it)->m_name <<"age is" <<(*it)->m_age<< endl; cout << "name is" << p->m_name << "age is" << p->m_age << endl; } } int main() { test(); return 0; }
3.vector容器嵌套形式
#include<string> #include<iostream> #include<vector> #include<algorithm> using namespace std; void test() { vector<vector<int>> v; vector<int> v1; vector<int> v2; vector<int> v3; vector<int> v4; for (int i = 0; i < 4; i++) { v1.push_back(i + 1); v2.push_back(i + 2); v3.push_back(i + 3); v4.push_back(i + 4); }; v.push_back(v1); v.push_back(v2); v.push_back(v3); v.push_back(v4); for (vector<vector<int>>::iterator it = v.begin(); it != v.end(); it++) { for (vector<int>::iterator t = (*it).begin(); t != (*it).end(); t++) { cout << *t << " "; } } } int main() { test(); return 0; }