Pointers in Containers in C++ STL
There are different containers in C++ having their own features where if are adding extra functionality of pointer it will contribute in a different way. Although not all of the containers are useful in this context so let’s see a few of the containers which can be helpful.
There are 5 containers that can be helpful:
- Using vector
- Using array
- Using map
- Using pairs
- Using stack
How to create Pointers in Containers?
1. Using Vector
Using vectors to create a container of pointers is the most easiest and effective way. It is easy to use also as a vector has dynamic size we can store as many addresses as we want.
42 51 66
2. Using Arrays
Can also be called a Pointer array as each element of the array stores the memory address of the variable.
Arrays contains 6294936 0 -554512983 32640 1
3. Using the map
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values.
The use of a Pointer is quite common with conditions where we want to store an address as a value and a fixed value as a key. For example, we can use it with Linked Lists or with Trees, wherever Nodes are being used.
Address(Key) String(ELEMENT) 0x7ffce12ebeb0 Hello 0x7ffce12ebec0 world
4. Using Pairs
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second).
Pair can be quite helpful where we want to store a value and address simultaneously.
String Address pointer gfg 0x7fff1e7ceab0
5. Using stack
Stacks are a type of container adapter with LIFO(Last In First Out) type of work, where a new element is added at one end (top) and an element is removed from that end only.
A pointer can be used with stack in a few cases where we want to store addresses rather than values.
Address of the inserted elements Address:0x7ffc39b9eec4 Value:20 Address:0xde62c0 Value:10
Please Login to comment...