C++ pair & tuple
In this page:
Working with std::pair
std::pair is a simple container that stores exactly two values together as a single unit, and those two values are allowed to be of entirely different data types — commonly used for things like a key paired with its associated value.
Example: Working with std::pair
#include <iostream>
#include <utility>
#include <string>
int main() {
std::pair<std::string, int> entry("age", 30);
std::cout << entry.first << " " << entry.second << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Working with std::tuple
std::tuple generalizes std::pair to hold any fixed number of values, each potentially of a different type, letting you group together more than two related pieces of data without needing to define a dedicated struct for a one-off case.
Example: Working with std::tuple
#include <iostream>
#include <tuple>
#include <string>
int main() {
std::tuple<int, std::string, double> record(1, "Alex", 3.5);
std::cout << std::get<0>(record) << " " << std::get<1>(record) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Unpacking with std::tie
You can unpack a tuple's individual elements directly into separate named variables using std::tie, which makes working with a function that returns multiple values feel almost as natural as working with ordinary multiple return values.
Example: Unpacking with std::tie
#include <iostream>
#include <tuple>
int main() {
std::tuple<int, int> point(3, 4);
int x, y;
std::tie(x, y) = point;
std::cout << x << " " << y << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Comparing Pairs and Tuples
C++ supports comparing pairs and tuples directly with relational operators; the comparison works lexicographically, checking the first elements first and only moving on to compare the next element if the first ones are equal.
Example: Comparing Pairs and Tuples
#include <iostream>
#include <utility>
int main() {
std::pair<int, int> a(1, 5);
std::pair<int, int> b(1, 3);
std::cout << (a > b) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chaining within Lists
Pairs are frequently stored inside a vector to group related records together compactly — for example, a vector of (name, score) pairs — letting you sort or search the whole collection using ordinary STL algorithms without a custom struct.
Example: Chaining within Lists
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <string>
int main() {
std::vector<std::pair<std::string, int>> scores = {{"Bob", 80}, {"Alice", 95}};
std::sort(scores.begin(), scores.end());
std::cout << scores[0].first << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: