之前在对于std内iterator的使用并没有太关心,一般是建立容器后,要进行遍历打印,查找之类的操作,但这种无需修改原来容器内的值的操作,比较好的策略是声明为const_iterator;
比如:
vector<int> lVec; lVec.push_back(1); lVec.push_back(2); lVec.push_back(3); std::vector<int>::const_iterator lIter = lVec.begin(); cout << *lIter << endl; lIter = lVec.begin()+1; cout << *lIter << endl; *lIter = 10;//Error will occur, *lIter shouldn't be changed. ++lIter;
但这样打印是可以的:
vector<int> lVec; lVec.push_back(1); lVec.push_back(2); lVec.push_back(3); for (vector<int>::const_iterator iter = lVec.begin(); iter != lVec.end(); ++iter) { cout << *iter << endl; }
但最爽的是利用boost::each,估计被boost优化掉了,等有时间看下它的实现:
vector<int> lVec; lVec.push_back(1); lVec.push_back(2); lVec.push_back(3); BOOST_FOREACH(int &aData,lVec) { cout << aData << endl; }