This post will discuss how to add a std::pair to a vector of pairs in C++.

1. Using std::emplace_back function

The standard solution to add a new std::pair to a vector of pairs is using the std::emplace_back(T&&... args) function, which in-place construct and insert a pair at the end of a vector, using the specified arguments for its constructor. Note that this function is added in C++11.

Its usage is demonstrated below:

Download  Run Code

Output:

(1, 2) (3, 4) (5, 6) (7, 8)

2. Using std::push_back function

Another simple solution is to add a new std::pair to a vector of pairs is using the std::push_back(T&& val) function, which either copies (or moves) a pair into the vector. A pair can be constructed in several ways:

⮚ Using std::make_pair function

Download  Run Code

Output:

(1, 2) (3, 4) (5, 6) (7, 8)

⮚ Using Aggregate Initialization

Download  Run Code

Output:

(1, 2) (3, 4) (5, 6) (7, 8)

⮚ Using Initialization Constructor

Download  Run Code

Output:

(1, 2) (3, 4) (5, 6) (7, 8)

That’s all about adding a new std::pair to a vector of pairs in C++.