【问题标题】:How is std::map overloading its subscript [] operator ? C++std::map 如何重载其下标 [] 运算符? C++
【发布时间】:2022-01-21 16:57:59
【问题描述】:
#include <iostream>
#include <map>
int main(void) {
  std::map<char, int> mapint;

  mapint.insert({'a', 1});
  mapint.insert({'b', 2});

  // subscript operator is overloaded to return iterator.second (the value with key 'a')
  int ex = mapint['a'];
  std::cout << ex << std::endl;
  // Why does this NOT traslate to 1=10 ?
  // instead it replaces or creates pair <'a',10>...
  mapint['a'] = 10;

  for (auto i : mapint) {
    std::cout << i.first << "," << i.second << std::endl;
  }
  
  // OUTPUT
// 1
// a,10
// b,2

  return 0;
}

map 运算符是如何被重载的?我尝试查看地图的代码,但找不到任何可以回答我的问题的东西... 我想为我的一门课做类似的事情,我认为弄清楚这一点应该会有很大帮助!

【问题讨论】:

标签: c++ c++11 stl hashmap


【解决方案1】:

它基本上只是建立在 map 中现有方法的基础之上。它的实现方式...

template<typename Key, typename Value>
struct map {

  // This operator cannot be declared 'const', since if the key 
  // is not found, a new items is automatically added. 
  Value& operator [] (const Key& key) {
    // attempt to find the key
    auto iter = find(key);

    // if not found... 
    if(iter == end()) {
    
      // insert new item (with a default value to start with)
      iter = insert(std::make_pair(key, Value()));
    }

    // return reference to the data item stored for 'key'
    return iter->second;    
  }
};

【讨论】:

    【解决方案2】:

    要重载 [] 运算符,您可以执行以下操作(在伪代码中):

    struct A
    {
        your_return_type operator[](your_argument_list)
        {
            your implementation
        }
    };
    

    如果您想返回对某个类成员的引用,那么您可能必须实现此运算符的 2 个版本,一个 const,它返回一个不可修改的引用,一个 non-const,它返回一个可修改的引用参考。

    struct A
    {
        your_modifiable_return_type_ref& operator[](your_argument_list)
        {
            your implementation
        }
    
    
        const your_non_modifiable_return_type_ref& operator[](your_argument_list) const
        {
            your implementation
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      相关资源
      最近更新 更多