Re: C++ Primer exercise 3.13
On Jul 19, 2:01 pm, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
On 2007-07-19 13:41, arnuld wrote:
[...]
#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::c=
in
>> 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..
That won't work either, since you'll still enter the loop when
there is only one element remaining (and thus add 2, resulting
in undefined behavior). Interpreting the requirements strictly,
I'd use something like:
while ( iter != end && iter + 1 != end ) {
// ...
iter +=2 ;
}
if ( iter != end ) {
// odd number...
}
Interpreting them a bit more loosely, I'd probably use a vector
of std::pair< int, int >, and handle the case of an odd number
of elements at input. (In a real world application, I'd
probably require two integers per line, and use getline to
read.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34