/* * Read some integers into an vector, then echo them, using iterators. */ #include #include using std::cin; using std::cout; using std::endl; int main() { // Read them in. std::vector vec; cout << "Enter some integers: " << endl; int val; while(cin >> val) { vec.push_back(val); } // Print them back out again. (Note: I could declare scan with auto // and save a lot of typing, but I wanted you to see the type name.) cout << "===============" << endl; for(std::vector::iterator scan = vec.begin(); scan < vec.end(); ++scan) { cout << *scan << " "; } cout << endl; // Array iterators can be compared, the result reflecting their // position, and they can incremented by numbers other than 1. // Here, we go up the even-numbered ones, and back down odd-numbered // ones. auto scan = vec.begin(); while(scan < vec.end()) { cout << *scan; scan += 2; if(scan < vec.end()) { cout << " "; } } std::string sep = "|"; for(scan = vec.begin() + 1; scan < vec.end(); scan += 2) { std::cout << sep << *scan; sep = " "; } cout << "\n===============" << endl; }