Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

I am writing a wrapper around an std::unorered_map however I am a little uncertain how I should provider a public member function to access the iteration provided by the ":" feature in C++11, for example:

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

How could I provide the same capability as above, via my wrapper around the unordered_map?

Tried 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;
    }

};
like image 709
user997112 Avatar asked Dec 09 '22 10:12

user997112


1 Answers

Just provide begin() and end() methods, returning suitable iterators.

Here's an 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;
}
like image 178
juanchopanza Avatar answered Dec 27 '22 10:12

juanchopanza