← Back to C++ Course | Chapter 13: STL Containers & Algorithms | Lesson 5 of 15

C++ pair & tuple

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.