在哈希图中实现分配运算符重载

我正在C中实现哈希图,但是,有一个我想做的操作

myMap["key"] = value; 

我该如何实施? 谢谢!

评论
  • 被窝里=
    被窝里= 回复

    First of all you need to implement the map's index access operator [], which should return a reference to the corresponding value.

    然后,使用该参考可以直接更新该值。

    Note: normally in C++ the map's operator [] automatically creates an entry when one does not exist.

    It's good to first create helper methods find(), which should return a (potentially empty) iterator, and insert() to create a new entry. Then operator [] can be implemented simply as:

    T& Map<T>::operator[] (Key const& key) {
        auto it = find(key);
        if it == end() {
            it = insert(std::make_pair(key, T::value_type()));
        }
        return it->second;
    }