c++ - 为 UDF std::unordered_map 提供 ":"运算符?

标签 c++ c++11

我正在围绕 std::unorered_map 编写一个包装器,但是我有点不确定我应该如何提供一个公共(public)成员函数来访问 C++11 中“:”特性提供的迭代,例如:

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

我如何通过围绕 unordered_map 的包装器提供与上述相同的功能?

尝试过的解决方案:

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

};

最佳答案

只需提供begin()end() 方法,返回合适的迭代器。

这是一个工作示例:

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

关于c++ - 为 UDF std::unordered_map 提供 ":"运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21410160/

相关文章:

c++ - 使用 boost::posix_time 时出现编译错误

c++ - 如何在 Windows 上的 MinGW 中更新 GCC?

c++ - 如何在 QListWidget 中为 QStringList 的每个项目显示一个 QLabel 和另一个 QString?

c++ - 与 C++03 相比,C++11 带来了哪些好处?

c++ - 我可以在 Rust 中就地构建吗?

c++ - 如何解析表示树状数据结构的字符串

c++ - 你能 static_assert 一个元组只有一种类型满足特定条件吗?

c++ - 做什么 ({});在 C++ 中是什么意思?

c++ - std::type_info::name() 的实际目的是什么?

c++ - gcc 4.8.2 在此默认的默认构造函数中调用复制构造函数是否正确?