Pair Manipulation
Accessing and Modifying Pair Elements
Pair manipulation involves various techniques to work with pair elements efficiently and safely.
1. Element Access
#include <utility>
#include <iostream>
int main() {
std::pair<int, std::string> pair1(42, "LabEx");
// Accessing elements
int first_value = pair1.first;
std::string second_value = pair1.second;
// Modifying elements
pair1.first = 100;
pair1.second = "Programming";
return 0;
}
2. Pair Comparison Operations
#include <utility>
#include <iostream>
int main() {
std::pair<int, std::string> pair1(42, "LabEx");
std::pair<int, std::string> pair2(42, "LabEx");
std::pair<int, std::string> pair3(100, "Programming");
// Comparison operators
bool equal = (pair1 == pair2); // true
bool not_equal = (pair1 != pair3); // true
bool less_than = (pair1 < pair3); // true
return 0;
}
Pair Manipulation Methods
Method |
Description |
Example |
swap() |
Exchange pair elements |
pair1.swap(pair2) |
tie() |
Unpack pair elements |
std::tie(x, y) = pair1 |
make_pair() |
Create new pair |
auto new_pair = std::make_pair(x, y) |
Pair Manipulation Workflow
graph TD
A[Pair Manipulation] --> B{Operation Type}
B --> |Access| C[first/second members]
B --> |Modify| D[Direct assignment]
B --> |Compare| E[Comparison operators]
B --> |Advanced| F[tie(), swap()]
Advanced Manipulation Techniques
#include <utility>
#include <tuple>
#include <iostream>
int main() {
// Using std::tie for unpacking
int x;
std::string y;
std::pair<int, std::string> pair1(42, "LabEx");
std::tie(x, y) = pair1;
// Structured bindings (C++17)
auto [value, text] = pair1;
// Swapping pairs
std::pair<int, std::string> pair2(100, "Programming");
pair1.swap(pair2);
return 0;
}
#include <utility>
#include <algorithm>
#include <vector>
int main() {
std::vector<std::pair<int, std::string>> pairs = {
{1, "LabEx"},
{3, "Programming"},
{2, "C++"}
};
// Sorting pairs
std::sort(pairs.begin(), pairs.end());
// Transforming pairs
std::transform(pairs.begin(), pairs.end(), pairs.begin(),
[](const auto& p) {
return std::make_pair(p.first * 2, p.second + " Advanced");
});
return 0;
}
Best Practices
- Use structured bindings for cleaner code
- Prefer
std::tie()
for multiple assignments
- Be cautious with pointer-based pairs
- Consider move semantics for performance
Error Handling in Pair Manipulation
#include <utility>
#include <stdexcept>
void validate_pair(const std::pair<int, std::string>& pair) {
if (pair.first < 0) {
throw std::invalid_argument("Negative value not allowed");
}
}