std::unordered_map pass by reference
c++
Solution
I am guessing your problem is that `operator[]` is non `const`, because it adds a default constructed element when accessed with a key that isn't already in the map. You can use `at()`, which assumes the key is present and throws an exception otherwise:
typedef unordered_map<uint64_t, mer*> mer_map;
void foo(const mer_map& m)
{
mer* val = m.at(key);
}
or use `std::unordered_map::find()`:
void foo(const mer_map& m)
{
auto it = m.find(key);
if (it != m.end())
{
// element is in map, use it
mer* val = it->second;
}
}
Note: You could also bypass the problem by passing a non-const reference, but by doing so you are saying the function would modify the map. You should only use a non-const reference if you really intend to modify an object.
void foo(mer_map& m)
{
mer* val = m[key];
}
Problem
I usually code in C. Now moving to C++. I have a `std::unordered_map` with 60 million entries. It is loaded once only and would not be modified later. I would like to pass it to some functions from time to time. But this code would copy the hash map every time: ``` typedef unordered_map<uint64_t, mer*> mer_map; void test_pass_by_ref3(mer_map kmers) { } void test_pass_by_ref2(mer_map kmers) { test_pass_by_ref3(kmers); } void test_pass_by_ref(mer_map kmers) { test_pass_by_ref2(kmers); } ``` If I want to pass the `pointer` only, how to pass it and query it as usual: `value = mer_map[key]`? I searched and find the `passing by reference` syntax: ``` void foo(const ClassName &name) { ClassName& temp = const_cast<ClassName&>(name); ... .... } ``` But it seems cannot compiled. Please help. Thanks.