计算在一个unordered_map范围内出现的次数

Counting number of occurrences in a range within an unordered_map

本文关键字:范围内 map unordered 一个 计算      更新时间:2023-10-16

我将我的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>>这样的东西作为平面地图。

现场演示。