Let’s say I have a vector of long long elements:
std::vector<long long>V {1, 2, 3};
I have seen that in order to iterate over the vector you can do this:
for (auto i = v.begin() ; i != v.end() ; i++) cout<<*i;
i++
means i
grows by 1
, but shouldn’t the address go up 8 bytes to print the next element? So “growing” part of the for loop(for any type) should look like this:
i += sizeof(v[0]);
I’m assuming an address can hold 1 byte , so if the starting address of an integer would be 1000 , then its total allocation will be represented by adresses:1000 , 1001 , 1002 , 1003.I would like to understand memory better so I’d be thankful if you could help me.
Answer
When you increment a pointer it goes up by the “size of” the pointer’s type. Remember, for a given pointer i
, i[0]
is the first element and is equivalent to *(i + 1)
.
Iterators tend to work in a very similar fashion so their operation is familiar, they feel like pointers due to how operator*
and operator->
are implemented.
In other words, the meaning of i++
depends entirely on what i
is and what operator++
will do on that type. Seeing ++
does not automatically mean +1
. For iterators it has a very specific meaning, and that depends entirely on the type.
For std::vector
it moves a pointer up to the next entry. For other structures it might navigate a linked list. You could write your own class where it makes a database call, reads a file from disk, or basically whatever you want.
Now if you do i += sizeof(v[0])
instead then you’re moving up an arbitrary number of places in your array. It depends on what the size of that entry is, which depends a lot on your ISA.
std::vector
is really simple, it’s just a straight up block of memory treated like an array. You can even get a pointer to this via the data()
function.
In other words think of i++
as “move up one index” not “move up one byte”.