Search code examples
c++vectorauto

Understanding .begin and .end in vectors


I'm learning vectors from this post and they start off with iterators. They define .begin and .end as follows:

begin() – Returns an iterator pointing to the first element in the vector

end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector

And then they give the following code snippet, I added the 3rd for loop to express my question.

#include<iostream>
#include<vector>

int main() {
    std::vector <int> g1; //creating a vector
    for (int i = 1; i <= 3; i++){
        g1.push_back(i);
    }
    std::cout << "Output of beginning and end values: ";
    for (auto i = g1.begin(); i != g1.end(); i++) {
        std::cout << *i << " "; 
    }
    std::cout << "\nOutput of beginning and end addresses: ";
    for (auto i = g1.begin(); i != g1.end(); i++) {
        std::cout << &i << " ";
    }
     //"Output of beginning and end values: 1 2 3"
     //"Output of beginning and end addresses: 0105FB0C 0105FB0C 0105FB0C"
    return 0;
}

My confusion is that the address of i stays the same, but the value that i has changed. Doesn't i* mean i is just dereferenced? So something has to be changing the value of i if it's address is not changing so that it would be able to have a different value. I think I may be confusing iterators with pointers. I know that auto is basically type inference but that's about it.

So my question is, how does the value of i change, if it's address is the same for every element in the vector?


Solution

  • &i is the address of the local variable i. This will not change. *i dereferences the iterator, and returns the value at that element of the vector. &*i will return a pointer to the element in the vector.

    So you loop should use

    std::cout << &*i << " ";
    

    to see the addresses change.