C++ Pointers
Pointers and STL Containers

Introduction

This C++ Pointer shows you how to manipulate pointers stored in an STL Vector and an STL Map. There are other STL containers, but once the use of these two containers is known the same techniques can be used for the others.

Why store a pointer in an STL container?

Overview of the Demonstration Program

To make the example easily understandable and focus on the code required for using the STL containers, rather than the application, the example code uses simple classes to handle HTML colour codes. The use cases are very simple and a bit contrived, but the aim is to show how to use a pointer stored in a container.

The demonstration program uses a base class that stores a 24-bit colour code and the colour name, ColourCode. The name of the colour and the colour value can't be changed in the base class. ColourCode objects are created from HTML colour code data for a small number of colours in Loader.cpp

A Vector is used to store unique_ptrs of colour code objects, not of pointers to the objects.

A number of objects of a class derived from ColourCode, that allows the colour code name and value to be changed, are created and added to the Vector of ColourCode objects created from the data file.

After the colour code data has been loaded a Vector is used to store a pointer for each ColourCode object, used for example to store the load order of the data. A redundant exercise, but done to demonstrate using a Vector of pointers.

A Map is created and used to store a pointer for each ColourCode object with a key, the colour code's name, to provide a fast look up of a colour code.

The contents of the Vector and Map are written to results.txt to demonstrate the contents of both the same.

The customisable ColourCode objects are changed to hold the 7 additional colours, (ignoring the second occurrence of black), of the 4-bit RGBI palette. The Map of pointers of the ColourCode objects is used to find the customisable ColourCode objects by name.

Because we can contain pointers to derived classes in a Container of pointers of the base class, a dynamic cast enables us to select a specific class that implements specific functionality, without having to fill the base class with all the virtual functions that are implemented somewhere in the inheritance tree.

DerivedClass* derived = dynamic_cast<DerivedClass* >((mapIteratorBase->second)); if (derived != NULL) derived->derivedClassSpecificFunction(args);

If the dynamic_cast is successful, i.e. not NULL we can easily do class specific actions on the object.

The contents of the Vector and Map are written to results.txt to demonstrate the contents of both contain the same updated data.

The Map and Vector of ColourCode pointers are cleared. When the Vector of ColourCodes is cleared, the destruction of the contained unique_ptrs is displayed.

This C++ Pointer assumes you know how to use a Vector or Map to hold primitives, as this is widely described in literature. If you want to know how to use the STL Vector or Map check out www.cppreference.com/cppstl.html or Google etc., for information on the Standard Template Library.

Please note that this C++ Pointer is distributed with
NO WARRANTY

Section 5 Disclaimer of Warranties and Limitation of Liability.

  1. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
  2. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
  3. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
.

How to Create a Map and Vector of Pointers

A Vector or Map of Pointers is created in the same way that a Vector or Map of primitives, objects or structs are created, (see my C++ Pointer Objects, structs and STL Containers) as shown following, (see TSSCppPtr4.cpp for actual code).

std::vector<class* > containerName; std::map<key type, class* > containerName;

How to Add an Pointer to an STL Container

A Pointer is added to an STL Container the same why that primitives, objects or structs are added, (see my C++ Pointer Objects, structs and STL Containers) as shown following, (see TSSCppPtr4.cpp for actual code).

vector.emplace_back(pointerToAdd); auto inserted = map.emplace(key, pointerToAdd);

Note in TSSCppPtr4.cpp, the Vector loadOrder is loaded with the pointer contained in the std::unique_ptr, so the pointer is obtained with .get() of the unique_ptr. In this example it's more convenient to load the Map colourCodeIndex with the pointer stored in Vector loaderOrder rather then extract the pointer from the Vector of ColourCode objects.

How to Create an Iterator for an STL Container of Pointers

An Iterator for an STL Container of Pointers is created in the same way that an iterator would be created for a Container of primitives, objects or structs are created, (see my C++ Pointer Objects, structs and STL Containers). The addition of type deduction, (auto) to C++ simplifies iterator creation and in this example only auto constructed iterators are used.

How to Access a Member Function of the Object or struct Pointed to by the Pointer Stored in an STL Container

The member functions of an object or struct pointed to by the Pointer in a Container are accessed the same as if the Container stored objects or structs, (see my C++ Pointer Objects, structs and STL Containers).

Using an iterator created for the Container, which is used as a pointer to the object, use the -> (structure pointer dereference) operator in place of the dot operator to access the object's or struct's member function. For example;

vectorIterator->functionName(args); mapIterator.second->functionName(args);

How to pass an Pointer Stored in an STL Container into a Function

A pointer in a Container can be passed into a function that takes a reference to the object, by dereferencing the iterator for the Container. For example

output(fout, *vectorIterator); output(fout, *mapIterator.second); … void output(std::ofstream &fout, Class &name); { name.functionName(args) …

Note, in the function the pointer referenced by the iterator is now treated as if it is an object so the member functions are referenced using the . (dot) operator.

A pointer in a Map can also be passed into a function that takes the reference of a Map Iterator, which you can do if you also want the value of the Map Key in the function, for example

output(fout, mapIterator); … void output(std::ofstream &fout, std::map<sub-key type, value type>::iterator &iteratorName) { … iteratorName->first … ; iteratorName->second.functionName(args); …

Note, because we are passing an iterator into the iterator reference parameter of a function, the iterator is not dereferenced in the function call, and within the function the variable is an iterator and the first and second parameters of the iterator are referenced with the -> (arrow) (pointer dereference) operator.

Software for Download and Installation

This C++ Pointer was compiled and tested using Apple clang version 14.0.0 on x86_64-apple-darwin22.3.0 and with Windows 10 using cygwin-3.2.0, gcc version 10.2.0

To obtain the source code, install and execute this C++ Pointer use the following procedure.

Description
Shell Commands
Download TSSCppPtr4.tar.gz and save to a folder
 
Extract TSSCppPtr4.tar.gz
Open a terminal window, navigate to the folder and expand the file using the command
$ tar -xvzf TSSCppPtr4.tar.gz
This will create the folder TSSCppPtr4 and place the source files in it
 
Go to the TSSCppPtr4 folder
$ cd TSSCppPtr4
Use your favourite text editor to view the file TSSCppPtr4.cpp, which contains the code to demonstrate using Pointers in a Vector and in a Map
 
Optionally
Build the executable
$ make
Run the example
$ ./TSSCppPtr4
Use your favourite text editor to view the results file
 

Revision History

Rev
Date
Details
0.0
27-Apr-2023
Initial version

Technical Support

Bug-Reports

If you suspect a bug please e-mail a description being sure to identify that the bug report is about C++ Pointer #4 and include as much detail as possible.