Insert a pair to a vector in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <utility> int main() { std::vector<std::pair<int, int>> pairs = {{1, 2}, {3, 4}, {5, 6}}; // add a new pair to vector using emplace_back() pairs.emplace_back(7, 8); // print all pairs for (auto p: pairs) { std::cout << "(" << p.first << ", " << p.second << ") "; } return 0; } |
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
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <utility> int main() { std::vector<std::pair<int, int>> pairs = {{1, 2}, {3, 4}, {5, 6}}; // add a new pair to vector using make_pair() pairs.push_back(std::make_pair(7, 8)); // print all pairs for (auto p: pairs) { std::cout << "(" << p.first << ", " << p.second << ") "; } return 0; } |
Output:
(1, 2) (3, 4) (5, 6) (7, 8)
⮚ Using Aggregate Initialization
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <utility> int main() { std::vector<std::pair<int, int>> pairs = {{1, 2}, {3, 4}, {5, 6}}; // add a new pair to vector using aggregate initialization pairs.push_back({7, 8}); // print all pairs for (auto p: pairs) { std::cout << "(" << p.first << ", " << p.second << ") "; } return 0; } |
Output:
(1, 2) (3, 4) (5, 6) (7, 8)
⮚ Using Initialization Constructor
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <utility> int main() { std::vector<std::pair<int, int>> pairs = {{1, 2}, {3, 4}, {5, 6}}; // add a new pair to vector using constructor pairs.push_back(std::pair<int, int>(7, 8)); // print all pairs for (auto p: pairs) { std::cout << "(" << p.first << ", " << p.second << ") "; } return 0; } |
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++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)