计算在一个unordered_map范围内出现的次数
Counting number of occurrences in a range within an unordered_map
我将我的unordered_map设置为:
unordered_map<int, deque<my_struct>> table;
当我向程序读取值时,我通常这样做:
table[int].push_back(obj);
我想要做的是如果给我两个整数变量,我想要找到在这两个变量之间出现的键的数量。
如果我的表中有这样的代码
table[49].push_back(obj);
table[59].push_back(obj);
table[60].push_back(obj);
如果我执行我的搜索函数(我目前正在尝试编写)来查找45和65之间的键值,我应该有3个结果。
我不太确定如何有效地处理这件事。任何想法都会很有帮助。比你。如果您使用的是std::unordered_map
,我认为您别无选择,只能循环遍历所有整数45到65,并使用find
来检查键是否存在于unordered_map
:
using my_table = std::unordered_map<int, std::deque<my_struct>>;
int count(const my_table& table, int begin, int end) {
int sum = 0;
for (int i = begin; i != end; ++i) {
auto find_result = table.find(i);
if (find_result != table.end())
sum++;
}
return sum;
}
但这可能不是很有效。如果您使用std::map
,则元素是有序的,因此可以更有效地实现:
using my_table = std::map<int, std::deque<my_struct>>;
int count(const my_table& table, int begin, int end) {
auto begin_itr = table.lower_bound(begin);
if (begin_itr == table.end())
return 0;
auto end_itr = table.lower_bound(end);
return std::distance(begin_itr, end_itr);
}
我使用了std::map::lower_bound
函数。
根据你的地图的稀疏程度,你甚至可以考虑使用像std::vector<std::deque<my_struct>>
这样的东西作为平面地图。
现场演示。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 错误:未在此范围内声明'reverse'
- 并行用于C++17中数组索引范围内的循环
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 不计算一个范围内的完美数
- 错误:"imread"未在此范围内声明
- 我在范围内未声明的错误类有问题
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- 我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?
- 未在此范围内声明错误 'xy'
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 命名空间范围内的外部 - GCC vs clang vs msvc
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 如何仅使用 While 循环在给定范围内找到可被 7 整除的计数整数
- Socklen_t未在此范围内声明
- 错误:'[' 之前预期的非限定 id 和错误:'users'未在此范围内声明
- 查找给定范围内最长连续 1 的频率
- "Main"已在当前范围内声明
- c++ 变量在宏的扩展中没有在这个范围内声明
- 如何在 std::map 中找到指定范围内的元素?