-4
int main() { vector g1; vector :: iterator i; vector :: reverse_iterator ir;

    for (int i = 1; i <= 5; i++)
        g1.push_back(i);

    cout << "Output of begin and end\t:\t";
    for (i = g1.begin(); i != g1.end(); ++i)
        cout << *i << '\t';

    cout << endl << endl;
    cout << "Output of rbegin and rend\t:\t";
    for (ir = g1.rbegin(); ir != g1.rend(); ++ir)
        cout << '\t' << *ir;

    return 0;

}

Here in this code variable "i" has been declared as a iterator as well as a variable inside a for loop. isn't that a error?

If we see the first for loop it say that the loop will run till i!=g1.end() that means that the value of *(g1.end()) should not be displayed by *i but it is giving. ide shows output 1 2 3 4 5 for me it should be 1 2 3 4.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    What is `vector`? Is it a type-alias of a specific `std::vector` template? When creating a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) that is supposed to build, make sure it actually does. – Some programmer dude Oct 19 '17 at 06:43
  • scoping matters – user2736738 Oct 19 '17 at 06:44
  • As for the variable `i`, a `for` loop creates its own scope for the definitions inside it. – Some programmer dude Oct 19 '17 at 06:44
  • 1
    For the second question (which is really a separate question and should have been posted as such) [this `std::vector::end` reference](http://en.cppreference.com/w/cpp/container/vector/end) should explain it. As should any [good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Some programmer dude Oct 19 '17 at 06:46

1 Answers1

0
  1. i is defined as an iterator in the argument list. When you redefine it in the first for loop, this is a new definition only for the scope of the loop -- this is perfectly legal, though not good practice.

  2. vector::end() points to memory after the final item, not to the final item. So, yes, the final item in the vector will be printed.

Eli
  • 693
  • 5
  • 12