Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question on vectors, pointers and iterators

Guys, I have a midterm examination tomorrow, and I was looking over the sample paper, and I'm not sure about this question. Any help would be appreciated.

Let v be a vector<Thingie*>, so that each element v[i] contains a pointer to a Thingie. If p is a vector<Thingie*>::iterator, answer the following questions:

  1. what type is p?
  2. what type is *p?
  3. what code provides the address of the actual Thingie?
  4. what code provides the actual Thingie?
like image 590
xbonez Avatar asked May 19 '10 00:05

xbonez


People also ask

Is vector iterator a pointer?

An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them.

How do you access vectors using iterators?

Vector's iterators are random access iterators which means they look and feel like plain pointers. You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [] .

Can you use pointers with vectors?

You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.

Why use iterators instead of pointers?

A pointer of type T* can point to any type T object. An iterator is more restricted, e.g., a vector::iterator can only refer to doubles that are inside a vector container.


1 Answers

what type is p?

p is of type vector<Thingie*>::iterator, whatever type that happens to be.

what type is *p?

*p is a Thingie*&; that is, it is a reference to the element in the vector at which the iterator points.

what code provides the address of the actual Thingie?

*p, since the elements of the vector are pointers to the Thingies, and *p gives a reference to the element in the vector.

what code provides the actual Thingie?

**p; that is, you dereference the pointer obtained by *p to obtain the referent of the pointer.

like image 135
James McNellis Avatar answered Sep 30 '22 16:09

James McNellis