简体   繁体   中英

Providing “:” operator for UDF std::unordered_map?

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

};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM