C++

C++ Vector of Pairs

In C++, a vector is a versatile container that can dynamically resize itself which allows for efficient manipulation of elements. While a pair is a simple container that can hold two heterogeneous objects which provides a convenient means to associate and manage the related data. When these pairs are organized within a vector, the developers gain the ability to create the dynamic collections of key-value pairs or any other combination of two distinct elements.

This data structure is particularly useful in scenarios where the elements must be stored as pairs such as when dealing with key-value pairs or representing the relationships between entities. In this article, we will explore the concept of a C++ vector of pairs and explore the various examples to illustrate its practical applications.

Example 1: Basic Usage: Iterating Over a Vector of Pairs

Let’s consider a basic example where we create a vector of pairs that represent the student names and their corresponding ages. Iterating over a vector of pairs is similar to iterating over a regular vector. One can employ either the iterators or range-based “for” loops to retrieve each pair within the vector.

This example showcases the syntax for a “vector of pairs” in a meaningful context.

#include <iostream>
#include <vector>
#include <utility>

int main() {
   
    std::vector<std::pair<std::string, int>> studentData;

    studentData.push_back(std::make_pair("Adam", 20));
    studentData.push_back(std::make_pair("Bill", 22));
    studentData.push_back(std::make_pair("Charlie", 21));

    std::cout << "Student Data:\n";
    for (const auto& student : studentData) {
        std::cout << "Name: " << student.first << ", Age: " << student.second << std::endl;
    }

    return 0;
}

 
In this C++ code snippet, we begin by including three essential header files: “<iostream>” for input and output operations, “<vector>” to utilize the vector container, and “<utility>” to access the “std::pair” template. These headers enable us to use the functionalities that are essential to our program.

Moving forward, within the main() function, we declare a vector named “studentData” using the “std::vector” container. This vector is designed to store the pairs where each pair encapsulates a student’s name (represented as an “std::string”) and their age (an “int” integer).  Then, we populate the “studentData” vector with three pairs. Using the “push_back” function, pairs are added to the end of the vector, dynamically adjusting its size. A loop then iterates through “studentData”, extracting and printing each student’s name and age. The output displays “Student Data:” which emphasizes the structured representation. Student names and ages are printed separately, clearly presenting the stored data.

Example 2: Sorting a Vector of Pairs

Sorting a vector of pairs is a common operation, especially when dealing with key-value associations. The “std::sort” function from the “<algorithm>” header can be used for this purpose. Let’s see how to sort a vector of pairs based on the first and second elements:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
   
    std::vector<std::pair<std::string, int>> info;

    info.push_back(std::make_pair("Peter", 15));
    info.push_back(std::make_pair("Dora", 29));
    info.push_back(std::make_pair("Hanna", 20));

    std::cout << "Original Information:\n";
    for (const auto& entry : info) {
        std::cout << "Name: " << entry.first << ", Age: " << entry.second << std::endl;
    }

 
    std::sort(info.begin(), info.end());

    std::cout << "\nSorted Information:\n";
    for (const auto& entry : info) {
        std::cout << "Age: " << entry.second << ", Name: " << entry.first << std::endl;
    }

    return 0;
}

 
In this C++ code example, we are working with a vector of pairs to store and manipulate the data related to individuals, specifically their names and ages. We initialize a vector named “info of pairs” within the main() function. Subsequently, we populate this vector with three pairs, each containing the name and age of a distinct person, utilizing the “push_back” function and “std::make_pair” for efficient pair creation.

We output the “Original Information” to the console. This involves iterating through the “info” vector and printing each pair’s components.  Then, we utilize the “std::sort” algorithm to rearrange the “info” vector based on the default comparison operator for pairs which compares the first element of each pair (in this case, the names). Following the sorting operation, we again iterate through the modified “info” vector by printing the sorted information. This time, the output emphasizes the age-first ordering, illustrating the result of the sorting process.

Example 3: Combining the Vectors of Different Types

You might encounter some situations where you must combine an information from two vectors. A vector of pairs can help maintain the association between elements from the two vectors.

#include <iostream>
#include <vector>

int main() {
    std::vector<std::string> cities = {"New York", "Paris", "Tokyo"};
    std::vector<int> populations = {8175133, 2140526, 37435191};

    std::vector<std::pair<std::string, int>> cityPopulationPairs;

    for (size_t i = 0; i < std::min(cities.size(), populations.size()); ++i) {
        cityPopulationPairs.push_back({cities[i], populations[i]});
    }

    std::cout << "City-Population Pairs:" << std::endl;
    for (const auto &pair : cityPopulationPairs) {
        std::cout << "City: " << pair.first << ", Population: " << pair.second << std::endl;
    }

    return 0;
}

 
In the code’s “main” function, two vectors are declared: “cities” to store the city names and “populations” to store the corresponding population values.

A third vector, “cityPopulationPairs”, is defined to store the pairs of cities and their respective populations. Each pair is “std::pair<std::string, int>” where “std::string” represents the city name and “int” represents the population. We then use a “for” loop iteration over the vectors (cities and populations) using “std::min” to ensure that the loop does not access the elements beyond the smaller of the two vector sizes. Inside the loop, pairs of city-population information are created and appended to the “cityPopulationPairs” vector.

After combining the information, another “for” loop is used to iterate through the pairs that are stored in “cityPopulationPairs”. The combined data is then displayed on the standard output using “std::cout”, clearly representing each city and its corresponding population.

Example 4: Finding the Maximum and Minimum Values

Identifying the minimum and maximum values within a dataset is a common requirement in algorithmic and statistical operations. We can use a vector of pairs to keep track of both the maximum and minimum values in a sequence:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {5, 12, 18, 3, 7, 4, 33};

    std::vector<std::pair<int, int>> minMaxPairs;

    std::sort(numbers.begin(), numbers.end());

    minMaxPairs.push_back({numbers.front(), numbers.back()});

    std::cout << "Min-Max Pairs:" << std::endl;
    for (const auto &pair : minMaxPairs) {
        std::cout << "Min: " << pair.first << ", Max: " << pair.second << std::endl;
    }

    return 0;
}

 
The provided C++ code demonstrates the process of finding the minimum and maximum values in a vector of integers and then storing these values in a vector of pairs. A vector named “numbers” is initially declared and initialized with a set of integers. To efficiently identify the minimum and maximum values in the dataset, the program utilizes the “std::sort” function from the algorithm library.

This function aims to arrange the elements in ascending order, simplifying the process of identifying both the minimum and maximum values in the dataset.  The sorting operation is applied to the “numbers” vector using numbers.begin() and numbers.end() as the range parameters. Following the sorting step, the program creates a vector of pairs, “minMaxPairs”, to store the calculated minimum and maximum values. The “push_back” function is then employed to add a single pair that contains the sorted numbers vector’s first (minimum) and last (maximum) elements. Finally, the program outputs the result by iterating through the “minMaxPairs” vector and displaying the minimum and maximum values.

Conclusion

In conclusion, the C++ vector of pairs emerges as a powerful and flexible data structure, adding a layer of versatility to programming tasks. Through a detailed exploration of its syntax and practical applications, we have seen how this container helps to organize the key-value associations, combine the information from different vectors, and track the minimum and maximum values.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content