Stats

Contributors: 7 Tuesday, September 20, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Using std::pair

Download c++ eBook

Example

The struct template std::pair can bundle together exactly two return values, of any two types:

#include <utility>
std::pair<int, int> foo(int a, int b) {
    return std::make_pair(a+b, a-b);
}

With C++11 or later, an initializer list can be used instead of std::make_pair:

C++11
#include <utility>
std::pair<int, int> foo(int a, int b) {
    return {a+b, a-b};
}

The individual values of the returned std::pair can be retrieved by using the pair's first and second member objects:

std::pair<int, int> mrvs = foo(5, 12);
std::cout << mrvs.first + mrvs.second << std::endl;

Output:

10