Providing the ":" operator for UDF std :: unordered_map?

I am writing a wrapper around std :: unorered_map, but I'm a little sure how I should provide a public member function to access the iteration provided by the ":" function in C ++ 11, for example:

//Iterate through all unoredered_map keys
for(auto x : my_map){
    //Process each x
}

How can I provide the same features as above through my wrapper around unordered_map?

Fixed solution:

#include <unordered_map>
#include <mutex>

template<typename T, typename K>
class MyClass{
private:
    std::unordered_map<T,K> map;
    std::mutex mtx;

public:

    MyClass(){}

    MyClass<T,K>(const MyClass<T,K>& src){
        //Going to lock the mutex
    }

    void insert(T key, K value){
        mtx.lock();
        map[T] = K;
        mtx.unlock();
    }

    K operator[](T key) const
    {
        return map[key];
    }

    K get(T key){
        return map[T];
    }

    decltype(map.cbegin()) begin() const 
    { 
        return map.begin(); 
    }

    decltype(map.cend()) end() const { 
        return map.end(); 
    }

    bool count(T key){
        int result = false;
        mtx.lock();
        result = map.count(key);
        mtx.unlock();
        return result;
    }

};
+4
source share
1 answer

Just specify the methods begin()and end()return the appropriate iterators.

Here is a working example:

#include <unordered_map>
#include <iostream>
#include <string>
struct Foo
{
  std::unordered_map<std::string, int> m;
  auto begin() const ->decltype(m.cbegin()) { return m.begin(); }
  auto end()   const ->decltype(m.cend())   { return m.end(); }

};


int main()
{
  Foo f{ { {"a", 1}, {"b", 2}, {"c",3} } };

  for (const auto& p : f)
    std::cout << p.first << " " << p.second << std::endl;

  std::cout << std::endl;
}
+14
source

Source: https://habr.com/ru/post/1524104/


All Articles