const函数 使用迭代器

如何在const成员数中访问stl::map呢?例如如下代码:

std::set<HuInfo> info = huSet[seat];
    for (std::set<HuInfo>::iterator it = info.begin(); it != info.end(); it++)
    {
        if (it->tile == tile)
            return true;
    }
    return false;

上面的代码会报错:error C2678: 二进制“[”: 没有找到接受“const std::map<_Kty,_Ty>”类型的左操作数的运算符(或没有可接受的转换)

这个错误说明const函数是不能直接访问map的,有如下三种方法解决:

 

(1)去掉函数const属性

  这种方法改变了原有设计,肯定是不行的。

(2)将stl::map成员声明为mutable

  这种方法更改了变量的特征,不过是可行的也符合逻辑的。

(3)通过const迭代器访问map成员

  这种方法最好,也是STL自带支持的const访问方式。参考代码修改如下:

 

std::map<int, std::set<HuInfo>>::const_iterator mit = huSet.begin();
    for(;mit != huSet.end();mit++)
    {
        if(mit->first == seat)
        {
            std::set<HuInfo> info = mit->second;
            for(std::set<HuInfo>::const_iterator it = info.begin();it != info.end();it++)
            {
                if(it->tile == tile)
                {
                    return true;
                }
            }
        }
        
    }

 

posted @ 2018-04-23 10:58  huluBrother  阅读(224)  评论(0)    收藏  举报