I am trying to write a simple program and have been trying to do it for a long time now with no sucess so though i should now ask for the solution:
c++ primer 4th ed, execise: 3.13:
"Read a set of integers into a vector. Calculate and print the sum of each pair of adjacent elements in the vector. If there is an odd number, tell the user and print the value of the last element without summing it."
I thought this was really simple - i have tried to do it with iterators - NB no subscripting of the vector elements. Unfortunately, cant seem to crack it. Someone said that myvector.end()-1 will get to the element of the last but one! but my book says that this would be the last element as end() ponints to nothing anyway.
The program gets stuck in an infinate loop & is not working. Any suggestions?
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main()
{
int sum(0); // to hold the sum
// read a set of integers into a vector
vector<int> mybox;
int mynumber;
cout << "Input some numbers into the vector- enter any letter to end input" << endl;
while(cin >> mynumber)
{
mybox.push_back(mynumber);
}
// processing phase. Need to know how many elements we have
vector<int>::size_type howmany;
howmany = mybox.size();
cout << "This vector has " << howmany << " elements!" << endl;
// do what needs to be done until howmany == 0
if (howmany % 2 != 0)
{
// the size is odd - sum adjacent elements except the last one. Just print that out.
cout << "The number of elements are odd" << endl;
for(vector<int>::iterator iter = mybox.begin(); iter != mybox.end() - 1; iter+2)
{
int pairs(0);
pairs = *iter + *(iter+1);
cout << pairs << endl;
}
cout << "The last number is ";
vector<int>::iterator secondit = mybox.end();
cout << *secondit << endl;
}
else
{
// the size is even
for(vector<int>::iterator iter = mybox.begin(); iter != mybox.end() - 1; iter+2)
{
int epairs(0);
epairs = *iter + *(iter+1);
cout << epairs << endl;
}
}
[code]"Please use code tags"[/code] for(vector<int>::iterator iter = mybox.begin(); iter != mybox.end() - 1; iter+2) You are not modifying iter.
Someone said that myvector.end()-1 will get to the element of the last but one! but my book says that this would be the last element as end() ponints to nothing anyway.
end() points to "nothing". When you reach end(), you should stop.
Another issue with your loop is that you are not handling even/odd properly.
You want to increment the iterator by 2, ¿what will happend if you jump over end() ?
An iterator doesn't know that it is invalid. If you wanted to do iter += 1000;, ¿how could it know that it can only increment 352 positions before become invalid?
Syntactically you can increment an invalid iterator. And that results in undefined behaviour.