7.1.4 Pointers and Data Structures

In this final example, you are going to explore how pointers impact data structures such as vectors, stacks, maps, etc. While the implementation is a variation on what you have already seen, there is a new syntax shortcut that will become an important tool in your toolbox.

Data Structure of Pointers

As you think of data structures and pointers, there are two scenarios. The first is a standard data structure that stores pointers.

In this case, the syntax is very similar to what you have seen so far. You create the data structure as you would usually:

queue<int*> nums;

int *num1;
num1 = new int;
*num1 = 50;
nums.push(num1);

cout << *nums.front() << endl;
nums.pop();

Notice that the data type for the queue is int*, which creates a queue of integer pointers. Once you have an integer pointer, it can be added to the queue.

To access the pointer, you access just like any other queue data type, however, if you want to get the value, you need to dereference after accessing it. Notice that you do not need to dereference the value when you remove it with pop.

It is important to note that the * is applied to nums.front() because it is nums.front() that returns the pointer.

Pointer Data Structure of Values

The second scenario is when you have a data structure that is in itself a pointer but holds actual values. In this case, the declaration is similar to declaring any other pointer variable, including creating a space in the heap.

For example, a pointer queue of integers would get declared like this:

queue<int> *nums;
nums = new queue<int>;

To call functions such as push, you must first dereference the data structure. Once the data structure is dereferenced, you can call the function.

(*nums).push(20);

Notice this time that the dereference only applies to the data structure name, not to the entire function call. With this in mind, the data structure needs parenthesis to force the dereference before the function call.

The Arrow Operator

Pointer data structures (or referenced data structures) including a struct pointer are common in C++, so to avoid having to use the * and ( )., an arrow -> can be used instead:

Equivalent Statements:

(*nums).push(20);
nums->push(20);

The former is seldom used in practice and this course will exclusively use the latter to represent calls to functions of pointer data structures.

Remember, the arrow operator is used in place of the dot anytime the root data structure is a pointer. This applies to things like queues, maps, etc, but also applies to things like pairs and structs.

Last updated