c++ vector容器遍历方式
#include <vector> #include <iostream> class Test { public: int a; int b; int c; Test() { a = 0; b = 0; c = 0; } } int main() { vector<Test> vecTest; for(int i = 0; i < 5; i++) { Test temp; a=i; b=i+1; c=i+2; vecTest.push_back(temp); } std::cout.setf(ios::left); std::cout.width(6); //一、通过数组下标遍历 for(int i = 0; i < vecTest.size(); i++) { std::cout << vecTest[i].a << vecTest[i].b << vecTest[i].c <<std::endl; } //二、通过迭代器遍历 for(vector<Test>::iterator iter = vecTest.begin();iter != vecTest.end();iter++) { std::cout << iter->a << iter->b << iter->c <<std::endl; } //三、C++11标准,auto关键字遍历 for(auto iter = vecTest.begin(); iter != vecTest.end(); iter++) { std::cout << iter->a << iter->b << iter->c <<std::endl; } for(auto i : vecTest) { std::cout << iter->a << iter->b << iter->c <<std::endl; } }