So I'm just starting to learn about iterators in the book I'm reading.
One of the exercises of the chapter is to go back to the last chaper and recreate a program made there which had the purpose of reading a set of integrers into a vector, then adding them in pairs, starting with the first and last integrers, then the second and second to last and so on.
In the last chapter I used subscripts to access the elements of the vector, but this time I'm supposed to use iterators.
Writing the program in itself is no big issue, but it seems highly inefficient in its current state since I have to add an int and a vector<int>::size_type to keep track of the position of the iterator so that I could stop it halfway through the vector.
My code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
#include <string>
#include <vector>
using std::string;
using std::cout;
using std::cin;
using std::endl;
using std::vector;
int main ()
{
vector<int> ivec;
int entry, count = 1;
vector<int>::size_type count2 = 0;
while (cin >> entry) ivec.push_back(entry);
for (vector<int>::const_iterator iter = ivec.begin();
count2 < ivec.size(); ++iter)
{
if (count2 != ivec.size() - 1)
{
cout << *iter << " + " << *(ivec.end() - count) << " = "
<< *iter + *(ivec.end() - count) << endl;
++count; count2 += 2;
}
else
{
cout << *iter << endl;
++count; count2 += 2;
}
}
return 0;
}
|
Is this really the best way to do it using the knowledge I have at the moment? (basically, if it's not used in this code I probably don't know about it yet)
The issue is mainly that in this program the iterator doesn't really do anything that couldn't have been done using subscripts and the values that the other variables supply me with.
Could I maybe somehow get a number out of the iterator so that I don't need to use the "count" variable and instead can write something like:
*(ivec.end() - iter) // though I know this doesn't work.