zoukankan      html  css  js  c++  java
  • 一个关于const 变量作为map键值的Bug

    struct Instance{
        int _type;
        AtrVec _attri_list;
        Instance(){
    
        }
        float getAttriValue(const proto::Attribute& attri) const{
            if(_attri_list.find(attri) == _attri_list.cend()){
                std::cout<<"ERROR : Attribute didn't exist ins AtrVec.";
            }
            return _attri_list.at(attri);
        }
    };
    

    这里当使用 cons Instance 调用函数时,只可以使用 const Attribute 作为键值,但是 map [] 运算符不是const函数,因此会报错,使用 map 的 at 方法可以避免,因为

          mapped_type&
          at(const key_type& __k)
          {
    	iterator __i = lower_bound(__k);
    	if (__i == end() || key_comp()(__k, (*__i).first))
    	  __throw_out_of_range(__N("map::at"));
    	return (*__i).second;
          }
    
          const mapped_type&
          at(const key_type& __k) const
          {
    	const_iterator __i = lower_bound(__k);
    	if (__i == end() || key_comp()(__k, (*__i).first))
    	  __throw_out_of_range(__N("map::at"));
    	return (*__i).second;
          }
    

    既有const 定义,又有非const 定义.

    参考

  • 相关阅读:
    每日一(水)题
    操作树学习笔记
    「THUSCH 2017」大魔法师
    几个规律
    DP专题(DP进阶题单 )
    康托展开&逆康托展开
    一道题目
    P5629 【AFOI-19】区间与除法 题解
    留言板
    NOIP2020考试总结
  • 原文地址:https://www.cnblogs.com/walnuttree/p/12200612.html
Copyright © 2011-2022 走看看