/*
* Read some integers into an vector, then echo them, using iterators.
*/
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
int main()
{
// Read them in.
std::vector<int> 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<int>::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;
}
This example contains a declaration giving the type as auto.
Modern C++ allows variables which which are given initial values to
be so declared, and it gives the variable the
type of the initial value. So:
auto bill = 4;
auto sally = 0.25 * bill;
makes bill an integer because it is given an integer value,
and sally is double because that's the type its initial expression.
This
auto mike;
is illegal since there is no initial value to specify the type.
This
does not provide dynamic typing; the type assigned by
the declaration is fixed, so
auto s = 0;
s = "Zero";
will not compile since the second statement is a type error. (Or, if you know Javascript, auto is not var.)
These small discussion examples
using simple types are legal, but auto is most useful
as seen in the larger example, where the type name is long and complex.