# 如何使用迭代器浏览vector？ （C ++）

` `using namespace std; vector<string> myvector; // a vector of stings. // push some strings in the vector. myvector.push_back("a"); myvector.push_back("b"); myvector.push_back("c"); myvector.push_back("d"); vector<string>::iterator it; // declare an iterator to a vector of strings int n = 3; // nth element to be found. int i = 0; // counter. // now start at from the beginning // and keep iterating over the element till you find // nth element...or reach the end of vector. for(it = myvector.begin(); it != myvector.end(); it++,i++ ) { // found nth element..print and break. if(i == n) { cout<< *it << endl; // prints d. break; } } // other easier ways of doing the same. // using operator[] cout<<myvector[n]<<endl; // prints d. // using the at method cout << myvector.at(n) << endl; // prints d.` `

` `vec.begin() // 1st vec.begin()+1 // 2nd // ... vec.begin()+(i-1) // ith // ... vec.begin()+(vec.size()-1) // last` `

` `int sum = 0; using Iter = std::vector<int>::const_iterator; for (Iter it = vec.begin(); it!=vec.end(); ++it) { sum += *it; }` `

` `sum = 0; for (Iter it = lst.begin(); it!=lst.end(); ++it) { sum += *it; }` `

` `sum = 0; std::for_each(vec.begin(), vec.end(), [&sum](int i) { sum += i; });` `

` `sum = 0; for (auto it = vec.begin(); it!=vec.end(); ++it) { sum += *it; }` `

` `sum = 0; for (auto value : vec) { sum += value; }` `

Vector的迭代器是随机访问迭代器，这意味着它们的外观和感觉像普通的指针。

` `std::vector<int> vec(10); std::Vector<int>::iterator it = vec.begin(); int sixth = *(it + 5); int third = *(2 + it); int second = it[1];` `

` `std::vector<int> vec(10); std::vector<int>::iterator it = vec.begin(); std::advance(it, 5); int sixth = *it;` `