In C++, the `std::pair` is a simple container defined in the Standard Library that holds two values or objects. It is particularly useful when you want to return two related values from a function or store pairs of data.
To construct a `std::pair`, you can use its constructor or the `make_pair` function. Once you have a pair, you can access its elements using the `first` and `second` public members.
// Including the necessary header
#include
#include // for std::pair and std::make_pair
using namespace std;
int main() {
// Creating a pair
pair p1; // Default constructor
p1.first = 1; // Assigning value to first
p1.second = "Apple"; // Assigning value to second
// Using make_pair to create a pair
pair p2 = make_pair(2, "Banana");
// Accessing and displaying pair elements
cout << "First pair: " << p1.first << ", " << p1.second << endl;
cout << "Second pair: " << p2.first << ", " << p2.second << endl;
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?