c++ - Counting number of occurrences in a range within an unordered_map -
i have unordered_map set as:
unordered_map<int, deque<my_struct>> table;
when read values program, do:
table[int].push_back(obj);
what want able if i'm given 2 integer variables, want able find number of keys occur between two.
so if in table have code like
table[49].push_back(obj); table[59].push_back(obj); table[60].push_back(obj);
if execute search function(which i'm trying write) between key values of 45 , 65, should have 3 results.
i'm not sure how go in efficient manner. ideas helpful. you.
if using std::unordered_map
don't think have choice loop on integers 45 65 , use find
check if key exists in 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; (int = begin; != end; ++i) { auto find_result = table.find(i); if (find_result != table.end()) sum++; } return sum; }
but may not efficient. if use std::map
instead elements ordered can achieved more efficiently:
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); }
i've used std::map::lower_bound
function.
depending on how sparse map might consider using std::vector<std::deque<my_struct>>
flat map.
Comments
Post a Comment