Associative Arrays In C++ - C++ Programming Tutorial
C++ Course / Arrays / Associative Arrays In C++

Associative Arrays In C++

BLUF: Mastering Associative Arrays In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Associative Arrays In C++

C++ is renowned for its efficiency. Learn how Associative Arrays In C++ enables low-level control and high-performance computing in the tutorial below.

In this guide, we will explore Associative containers in C++ along with their characteristics and illustrations.

In the C++ programming language, Associative arrays are data structures that link keys with values. They are effective for storing and fetching values using their respective keys. These associative arrays are created using different containers offered by the Standard Template Library. The main containers used for associative arrays are map and unordered_map. These containers enable us to establish relationships between keys and values. They are flexible and robust data structures that are valuable for solving a range of problems.

Essential features of the Associative arrays in C++:

Key-Value Mapping: Associative arrays in C++ are characterized by their key-value pair association.

Each item within an associative array should exist solely within a key-value duo. In this structure, each key must be distinct, with each corresponding value tied to a single key. The data's value is directly linked to its respective key.

  • Diverse key data types:

Associative arrays support keys of various types such as integers, strings, objects, or custom data types.

  • Effective retrieval of values based on keys:

These data structures are designed for the quick retrieval of elements by their keys. Retrieving a value by its key is more efficient than scanning through a standard array.

  • Flexible size and Insertion:

Associative arrays have the ability to expand as new key-value pairs are introduced and contract when key-value pairs are deleted, ensuring no issues arise concerning array size management.

Common operations in Associative Arrays:

There are various typical actions performed on associative arrays. Some primary functions in associative arrays include:

  • Insertion:

This process involves appending a fresh key-value combination to associative arrays by employing either square brackets or the insert function within C++.

  • Retrieving Elements:

Retrieving fetches the value linked with a particular key. When the key exists within the array, we can retrieve its value by referencing it. If the key is not currently present, a new entry is generated with a default value.

  • Modifying Elements:

Modifying enables changing the value linked to a particular key, while also generating a new key-value pair if the key is not already in the array.

  • Elimination:

This process involves eliminating a specific key-value pair within the associative array. The erase function is frequently employed for this task.

  • Validating Presence:

The find method verifies the presence of a specific key within the associative array. It provides the iterator pointing to the element if the key is found in the array. If the key is not found, it returns end.

  • Dimension:

The size function is utilized to determine the size of the associative array.

These fundamental actions are essential for modifying and retrieving data from associative arrays in C++. These specialized arrays provide quicker average search times. The time complexities linked with these actions become crucial, particularly when working with extensive datasets.

Applications of associative arrays in C++:

  • These are used in various scenarios where efficient key-based data retrieval is vital. These are used in dictionaries, database indexing, symbol tables, configuration management, caching, counting occurrences, graph algorithms, task scheduling, memorization, frequency analysis, http service, and configuration management.
  • In caching systems , associative arrays can store frequently accessed data with unique keys, enabling fast retrieval and reducing the need to fetch data from a slower source.
  • When a programmer deals with graph algorithms, associative arrays represent adjacency lists, mapping each vertex to its list of neighbouring vertices.
  • When a programmer is solving a program related to dynamic programming and recursion, associative arrays can be used for memorization, which stores the previously computed results to avoid false computations.
  • In web development, associative arrays can represent HTTP headers , where the header names are keys, and the corresponding values are the header values.
  • Now, we will discuss about some of the associative arrays:

These data structures are organized as binary trees that are sorted and uphold a specific order of keys. This particular type is widely employed in software development.

  • Unordered_map:

It incorporates a hash table to offer quicker insertion and retrieval compared to a map. In this case, the sequence of adding key-value pairs is not preserved.

  • Multimap:

It shares similarities with a map, although it permits duplicate key-value pairs, facilitating the storage of multiple elements with identical keys.

  • Unordered_multimap:

It functions akin to unordered_map and is constructed through the utilization of a hash table. It permits the storage of multiple elements associated with identical keys.

Example:

Let's consider a C++ code example to demonstrate the usage of the unordered_map container:

Example

#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
 unordered_map<int, string> myUnorderedMap;
 // Insertion
 myUnorderedMap[1] = "One";
 myUnorderedMap[2] = "Two";
 myUnorderedMap[3] = "Three";
 // Accessing
 cout << "Value for key 2: " << myUnorderedMap[2] << endl;
 // Updating
 myUnorderedMap[2] = "New Two";
 // Deleting
 myUnorderedMap.erase(1);
 // Printing all elements
 cout << "All elements in the unordered_map:\n";
 for (const auto& pair : myUnorderedMap) {
 cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
 }
 return 0;
}

Output:

Example 2:

Let us take a C++ program to illustrate the map :

Example

#include <iostream>
#include <map>
using namespace std;
int main() {
 map<int, string> myMap;
 // Insertion
 myMap[1] = "One";
 myMap[2] = "Two";
 myMap[3] = "Three";
 // Accessing
 cout << "Value for key 2: " << myMap[2] << endl;
 // Updating
 myMap[2] = "New Two";
 // Deleting
 myMap.erase(1);
 // Printing all elements
 cout << "All elements in the map:\n";
 for (const auto& pair : myMap) {
 cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
 }
 return 0;
}

Output:

Example 3:

Let's consider a C++ code example to demonstrate the functionality of multimap:

Example

#include <iostream>
#include <map>
using namespace std;
int main() {
 multimap<int, string> myMultimap;
 // Insertion
 myMultimap.insert({1, "One"});
 myMultimap.insert({2, "Two"});
 myMultimap.insert({2, "Another Two"}); // Allows duplicate keys
 // Accessing
 cout << "Values for key 2:\n";
 auto range = myMultimap.equal_range(2);
 for (auto it = range.first; it != range.second; ++it) {
 cout << "Value: " << it->second << endl;
 }
 // Deleting
 myMultimap.erase(1);
 // Printing all elements
 cout << "All elements in the multimap:\n";
 for (const auto& pair : myMultimap) {
 cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
 }
 return 0;
}

Output:

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience