Re: C++ Primer exercise 3.13
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?= <Erik-wikstrom@telia.com> wrote in
news:ToIni.4399$ZA.1859@newsb.telia.net:
On 2007-07-19 13:41, arnuld wrote:
On Thu, 19 Jul 2007 09:23:21 +0000, Erik Wikstr??m wrote:
Sorry, but you have not solved the problem the author intended.
First of you should let the user enter the numbers. Then you should
print the sum of each pair of numbers, but if the user entered an
odd number of numbers you can't sum the last element with another so
you you should just print it:
ok, BTW, i found the statement ambiguous. so i created the programem
on that basis of what it could mean.
So an example run could look something like this: -- Please enter
some numbers:
1
2
3
4
5
You entered an odd number of numbers.
The sums of the pairs are:
3
7
5
sorry, after 1.5 hours of grueling work, my new programme still gives
"segmentatioon fault" on finding an odd list of numbers. for even
amount of numbers this programme works:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> ivec; /* empty vector */ int v_num;
std::cout << "Please enter some numbers: " << std::endl;
while(std::cin
>> v_num)
ivec.push_back(v_num);
if((ivec.size() % 2) != 0)
{
std::cout << "oops!, you enetered an odd number of numbers" <<
std::endl;
}
std::cout << "The sum of the pairs are: " << std::endl; /* actual
programme */
for(std::vector<int>::const_iterator iter = ivec.begin(); iter !=
ivec.end(); iter += 2)
Replace the check to a less than (iter < ivec.end()), since you are
increasing the iterator with 2 each step you will step over ivec.end()
if the number of elements is odd..
Caveat: this is not good general advice. Testing for != end() is better
than testing for < end() as it is how one does the same sort of test for
the other containers. May work for vectors, won't work for the other
containers.
Finally, assuming that the += 2 steps past the end() iterator, isn't it
technically undefined behaviour to make the comparison as you would be
comparing a pointer to an element within an array (one-past-the-end
pointer is still considered to be "within the array") to a pointer that
isn't in the same array (and isn't 0)?
{
if((iter + 1) == ivec.end())
{
std::cout << *iter << std::endl;
Or add break; here.
I think this may be a better choice. Then again, I'd probably using
indexing for this instead of iteration (which does pretty much tie me to
vector...). Or perhaps use a while loop instead of a for.
}
else
{
std::cout << *iter + *(iter + 1) << std::endl;
}
}
return 0;
}