Store Two Variables in C++ unordered_set
An unordered_set in C++ is a container that stores unique elements in an unordered manner. It can store elements of any custom type, including cases where it saves two variables.
To store two variables, you can use a custom struct or class as the element type in an unordered_set. Here is an example using a custom struct:
#include <iostream>
#include <unordered_set>
struct MyPair {
int x;
int y;
};
struct MyPairHash {
size_t operator()(const MyPair& pair) const {
return std::hash<int>()(pair.x) ^ std::hash<int>()(pair.y);
}
};
struct MyPairEqual {
bool operator()(const MyPair& lhs, const MyPair& rhs) const {
return lhs.x == rhs.x && lhs.y == rhs.y;
}
};
int main() {
std::unordered_set<MyPair, MyPairHash, MyPairEqual> mySet;
mySet.insert({1, 2});
mySet.insert({3, 4});
mySet.insert({1, 2}); // 重复的元素不会被插入
for (const auto& pair : mySet) {
std::cout << pair.x << ", " << pair.y << std::endl;
}
return 0;
}
In the example above, MyPair is a custom struct that includes two integer variables x and y. MyPairHash is a custom hash function used to calculate the hash value of MyPair type. MyPairEqual is a custom equality comparison function used to determine if elements of MyPair type are equal.
In the main function, an unordered_set object called mySet is created and several elements of the type MyPair are inserted using the insert function. Note that duplicate elements will not be inserted because the elements in the unordered_set are unique.
Finally, iterate through mySet with a for loop and output the values of the member variables x and y for each MyPair element.
You can customize the member variables, hash function, and equal comparison function of the MyPair struct according to your own requirements.