As you mentioned “I did not understand what the code is doing”, let me briefly describe how to iterate through a container:
The long way:
vector<int> result = { 1,2,3 };
for (vector<int>::iterator it = result.begin(); it != result.end() ; it++) {
int i = *it;
cout << i << " ";
}
Each container provides an iterator, which you can think of a pointer moving forward along the elements of the container. begin()
returns a pointer to the first element, end()
returns a pointer to 1 past the last element. Dereferencing the iterator gives the actual value.
For above long way, with range-based for loops, C++ provides a shorthand notation with about the same meaning (i.e. it makes use of the iterator-concept but is less “clumsy” in notation):
for (auto i : result) {
cout << i << " ";
}
Try it out; hope it helps.
1
solved Printing contents of a vector [duplicate]