Monday, 15 March 2010

C++ Primer 5th Edition exercise 3.24 - iterators in vectors -



C++ Primer 5th Edition exercise 3.24 - iterators in vectors -

i started learning c++ myself using lippman, lajoie & moo's c++ primer 5th edition (5th printing, may 2014) in september 2014. exercises in book do, had here help , @ 1 i'm stuck days. searched google, blogs , other forums , got nothing, inquire help. exercise 3.24 @ page 113, asks same exercise 3.20 in page 105, using iterators:

read set of integers vector. print sum of each pair of adjacent elements. alter programme prints sum of first , lastly elements, followed sum of sec , second-to-last, , on.

using iterators asked, first part:

#include <iostream> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; int main() { vector<int> lista; int num_entra = 0; while (cin >> num_entra) lista.push_back(num_entra); cout << "sum of adjacent pairs: " << endl; (auto = lista.begin(); != lista.end() - 1; ++it) { *it += *(it + 1); cout << *it << ' '; } homecoming 0; }

the code above works intended, part need sum first , last, sec , sec last... etc. has issue can't solve:

int main() { vector<int> lista; int num_entra = 0; while (cin >> num_entra) lista.push_back(num_entra); auto ult = lista.end(); cout << "sum of first , lastly elements until center: " << endl; (auto = lista.begin(); != lista.end() - 1; ++it) { *it = *it + *(--ult); cout << *it << ' '; } homecoming 0; }

if user enters 1 2 3 4 5 6, programme adds 1 + 6, 2 + 5 , 3 + 4 should, adds lastly result (7) 5 , 6 , can't seem find way stop behavior. can programme shows 1 sum each pair until center of list? give thanks in advance.

one way utilize 2 iterators

auto front end = lista.begin(); // start @ front end , increment auto = lista.end() - 1; // start @ , decrement (; > front; // stop when iterators cross each other ++front, --back) { int total = *front + *back; std::cout << total << ' '; }

c++ vector iterator

No comments:

Post a Comment