Pair Manipulation
Basic Element Access
std::pair<int, string> dataPair(42, "LabEx");
// Accessing elements
int value = dataPair.first;
string text = dataPair.second;
Modification Techniques
Direct Assignment
std::pair<int, string> pair(10, "Initial");
pair.first = 20;
pair.second = "Updated";
Swap Operation
std::pair<int, string> pair1(1, "First");
std::pair<int, string> pair2(2, "Second");
std::swap(pair1, pair2); // Swap entire pairs
Comparison Operations
graph LR
A[Pair Comparison] --> B[== Equality]
A --> C[!= Inequality]
A --> D[< Less Than]
A --> E[> Greater Than]
Comparison Example
std::pair<int, string> p1(10, "A");
std::pair<int, string> p2(10, "B");
bool isEqual = (p1 == p2); // Compares first, then second
bool isLess = (p1 < p2);
Advanced Manipulation
Structured Binding (C++17)
std::pair<int, string> pair(100, "Modern");
auto [number, text] = pair;
Operation |
Method |
Example |
Tie |
std::tie |
std::tie(x, y) = pair |
Make Pair |
std::make_pair |
auto newPair = std::make_pair(x, y) |
Use Cases in Algorithms
vector<pair<int, string>> data = {
{3, "Three"},
{1, "One"},
{2, "Two"}
};
// Sorting pairs
std::sort(data.begin(), data.end());
- Lightweight container
- Minimal overhead
- Efficient for small data sets
- Supports move semantics
Mastering pair manipulation empowers you to write more expressive and efficient C++ code in your LabEx projects.