map使用技巧——1:c++中在map中放一个pair(int,int)和一个bool类型
如果需要自定义排序规则,可以提供一个比较函数或函数对象作为。
·
在 C++ 中,如果想在 std::map 中存储一个 std::pair<int, int> 作为键(key),并关联一个 bool 类型的值(value),可以按照以下方式实现:
1. 定义 std::map
#include <iostream>
#include <map>
#include <utility> // for std::pair
int main() {
// 定义 map,键是 std::pair<int, int>,值是 bool
std::map<std::pair<int, int>, bool> myMap;
// 插入数据
myMap[std::make_pair(1, 2)] = true;
myMap[std::make_pair(3, 4)] = false;
// 访问数据
std::cout << "Value for key (1, 2): " << myMap[std::make_pair(1, 2)] << std::endl;
std::cout << "Value for key (3, 4): " << myMap[std::make_pair(3, 4)] << std::endl;
return 0;
}
2. 代码说明
- 键类型:
std::pair<int, int>,表示一个由两个整数组成的键。 - 值类型:
bool,表示与键关联的值。 - 插入数据:使用
std::make_pair创建std::pair<int, int>作为键,并将其与bool值关联。 - 访问数据:通过键访问对应的值。
3. 示例输出
Value for key (1, 2): 1
Value for key (3, 4): 0
4. 注意事项
-
std::pair的比较:std::map默认使用std::less对键进行排序。std::pair的比较规则是:先比较first,如果first相等,再比较second。因此,std::pair<int, int>可以直接用作std::map的键。 -
自定义排序规则:
如果需要自定义排序规则,可以提供一个比较函数或函数对象作为std::map的第三个模板参数。例如:auto comp = [](const std::pair<int, int>& a, const std::pair<int, int>& b) { return a.first + a.second < b.first + b.second; // 按 pair 的和排序 }; std::map<std::pair<int, int>, bool, decltype(comp)> myMap(comp); -
性能:
std::map是基于红黑树实现的,插入、删除和查找操作的时间复杂度为O(log n)。
5. 扩展:使用 std::unordered_map
如果不需要对键进行排序,可以使用 std::unordered_map,它基于哈希表实现,插入、删除和查找操作的平均时间复杂度为 O(1)。但需要为 std::pair<int, int> 提供哈希函数。
#include <iostream>
#include <unordered_map>
#include <utility>
// 自定义哈希函数
struct pair_hash {
template <class T1, class T2>
std::size_t operator()(const std::pair<T1, T2>& p) const {
auto hash1 = std::hash<T1>{}(p.first);
auto hash2 = std::hash<T2>{}(p.second);
return hash1 ^ (hash2 << 1); // 或者使用 boost::hash_combine
}
};
int main() {
// 定义 unordered_map,键是 std::pair<int, int>,值是 bool
std::unordered_map<std::pair<int, int>, bool, pair_hash> myMap;
// 插入数据
myMap[std::make_pair(1, 2)] = true;
myMap[std::make_pair(3, 4)] = false;
// 访问数据
std::cout << "Value for key (1, 2): " << myMap[std::make_pair(1, 2)] << std::endl;
std::cout << "Value for key (3, 4): " << myMap[std::make_pair(3, 4)] << std::endl;
return 0;
}
6. 总结
- 在
std::map中,可以直接使用std::pair<int, int>作为键,关联bool类型的值。 - 如果需要更高效的查找,可以使用
std::unordered_map,但需要为std::pair<int, int>提供自定义哈希函数。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)