0
0
CppHow-ToBeginner · 3 min read

How to Create Vector of Pairs in C++: Syntax and Examples

In C++, you can create a std::vector of std::pair by specifying the pair type inside the vector template, like std::vector>. Each pair holds two values, and the vector stores multiple such pairs in order.
📐

Syntax

To create a vector of pairs, use the following syntax:

  • std::vector: A dynamic array that can grow in size.
  • std::pair<T1, T2>: A container holding two values of types T1 and T2.
  • Combine them as std::vector<std::pair<T1, T2>> to store multiple pairs.
cpp
std::vector<std::pair<int, int>> vec_of_pairs;
💻

Example

This example shows how to create a vector of pairs, add pairs to it, and print the pairs.

cpp
#include <iostream>
#include <vector>
#include <utility> // for std::pair

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

    // Add pairs to the vector
    vec_of_pairs.push_back(std::make_pair(1, 100));
    vec_of_pairs.push_back({2, 200}); // using initializer list
    vec_of_pairs.emplace_back(3, 300); // constructs pair in place

    // Print all pairs
    for (const auto& p : vec_of_pairs) {
        std::cout << "(" << p.first << ", " << p.second << ")\n";
    }

    return 0;
}
Output
(1, 100) (2, 200) (3, 300)
⚠️

Common Pitfalls

Common mistakes when working with vector of pairs include:

  • Forgetting to include <utility> for std::pair.
  • Using incorrect syntax for adding pairs (e.g., pushing raw values instead of pairs).
  • Not using emplace_back or make_pair to create pairs properly.

Example of wrong and right ways:

cpp
#include <vector>
#include <utility>

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

    // Wrong: pushing raw ints (won't compile)
    // vec.push_back(1, 2); 

    // Right: use make_pair
    vec.push_back(std::make_pair(1, 2));

    // Or use initializer list
    vec.push_back({3, 4});

    // Or emplace_back
    vec.emplace_back(5, 6);

    return 0;
}
📊

Quick Reference

Summary tips for vector of pairs in C++:

  • Include <vector> and <utility>.
  • Declare as std::vector<std::pair<T1, T2>>.
  • Add pairs using push_back(std::make_pair(...)), push_back({..., ...}), or emplace_back(..., ...).
  • Access pair elements with pair.first and pair.second.

Key Takeaways

Use std::vector> to store multiple pairs in C++.
Add pairs with push_back(std::make_pair(...)), push_back({..., ...}), or emplace_back(..., ...).
Access pair elements using .first and .second members.
Include and headers to use vector and pair.
Avoid pushing raw values; always create pairs before adding to the vector.