Author: Hayden Smith
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> names;
for (auto iter = names.begin(); iter != names.end(); ++iter) {
std::cout << *iter << "\n";
}
for (std::vector<std::string>::iterator iter = names.begin(); iter != names.end(); ++iter) {
std::cout << *iter << "\n";
}
}
demo204-iter1.cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> ages;
ages.push_back(18);
ages.push_back(19);
ages.push_back(20);
// type of iter would be std::vector<int>::iterator
for (auto iter = ages.begin(); iter != ages.end(); ++iter) {
(*iter)++; // OK
}
// type of iter would be std::vector<int>::const_iterator
for (auto iter = ages.cbegin(); iter != ages.cend(); ++iter) {
//(*iter)++; // NOT OK
}
// type of iter would be std::vector<int>::reverse_iterator
for (auto iter = ages.rbegin(); iter != ages.rend(); ++iter) {
std::cout << *iter << "\n"; // prints 20, 19, 18
}
// Can also use crbegin and crend
}
demo205-iter2.cpp
#include <fstream>
#include <iostream>
#include <iterator>
int main() {
std::ifstream in("data.in");
std::istream_iterator<int>begin(in);
std::istream_iterator<int> end;
std::cout << *begin++ << "\n"; // read the first int
++begin; // skip the 2nd int
std::cout << *begin++ << "\n"; // read the third int
while (begin != end) {
std::cout << *begin++ << "\n"; // read and print the rest
}
}
demo206-iter3.cpp