Understanding Pointers.

Help understanding exactly what is going on here.

1
2
3
4
5
6
7
8
9
10
int placeTreePosition(vector<int>& vec){
	for (auto it = vec.begin() + 1; it != vec.end(); ++it){
		if (*it == 0)
		{
			//int pos = it - vec.begin();
			return it - vec.begin();
		}
	}
	
}


Okay so &vec means that this function is receiving not a vector, but pointer to it's address in memory.
auto it = vec.begin() + 1 I'm not sure exactly what it is at the moment, I assume it will be the first memory pointer of the vector. If so, how can I +1 to it? What if the next memory address has nothing to do with this vector? Is +1 adding an int? Is it a string?
return it - vec.begin(); Why is it that this doesn't return a memory address? It actually returns the position of the vector element. If the position of the vector element is just a number, why can't auto be changed to int?
Last edited on
Okay so &vec means that this function is receiving not a vector, but pointer to it's address in memory.

No, it isn't a pointer, it's a reference, references are similar but not quite the same as a pointer.

auto it = vec.begin() + 1 I'm not sure exactly what it is at the moment, I assume it will be the first memory pointer of the vector.

This is creating an iterator that points to the beginning of the vector, then goes to the next element by adding 1 to the iterator.
If so, how can I +1 to it?

This is an iterator, not a pointer. The two are similar but an iterator has some differences. But remember you can do addition with pointers.

What if the next memory address has nothing to do with this vector?

Then the loop would never run because the condition section of the loop would fail.
Is +1 adding an int? Is it a string?

No it's an iterator, associated to the vector vec.

You really need to do some review on iterators. Perhaps: http://www.cplusplus.com/reference/iterator/ and http://www.learncpp.com/cpp-programming/16-3-stl-iterators-overview/


shnabz wrote:
What if the next memory address has nothing to do with this vector?
jlb wrote:
Then the loop would never run because the condition section of the loop would fail.


Actually, if vec is empty, the initializer results in undefined behavior (you may not increment the end iterator) which means the conditional may succeed. Presumably a requirement for calling this function is that you do so with a non-empty vector. I would expect an assert at the beginning of this function.
Topic archived. No new replies allowed.