c ++ map as function parameter get warning info“discards qualifiers”

时间:2013-12-26 13:40:09

标签: c++ map

使用CPP地图,从eclipse编辑器获取警告信息。

Point find_shortest_node(const vector<Point> &openset,const   map<Point, int> &f_score,const map<Point, vector<int> > &f_direction) {

vector<Point>::iterator iner_iterator = openset.begin();
Point min_point = *iner_iterator;
while (iner_iterator != openset.end()) {
    if (f_score[*iner_iterator] < f_score[min_point]) {
        min_point = *iner_iterator;
    } 
        else if (f_score[*iner_iterator] == f_score[min_point]) {
            vector<int> temp1 = f_direction[*iner_iterator], temp2 =f_direction[min_point];
            if (temp1.size() < temp2.size()) {
            min_point = *iner_iterator;
            continue;
        }
    }
    iner_iterator++;
}
return min_point;

}

警告信息:

  

将'const std :: map'作为'_Tp&amp;的'this'参数传递std :: map&lt; _Key,_Tp,_Compare,_Alloc&gt; :: operator [](const _KT&amp;)[with _KT = Point,_Key = Point,_Tp = int,_Compare = std :: less,_Alloc = std :: allocator &gt;]'丢弃限定符[-fpermissive]

2 个答案:

答案 0 :(得分:1)

出于某种原因,Eclipse认为f_scoreconst。根据你的声明,它不是const,所以这看起来像是Eclipse编辑器的问题。

如果你有一个符合C ++ 11的编译器,你可以使用map::at而不是方括号[]运算符解决这个问题,如下所示:

while (iner_iterator != openset.end()) {
    if (f_score.at(*iner_iterator) < f_score.at(min_point)) {
        min_point = *iner_iterator;
    } else if (f_score.at(*iner_iterator) == f_score.at(min_point)) {
            vector<int> temp1 = f_direction.at(*iner_iterator), temp2 =f_direction.at(min_point);
            if (temp1.size() < temp2.size()) {
            min_point = *iner_iterator;
            continue;
        }
    }
    iner_iterator++;
}

答案 1 :(得分:0)

最简单的解决方案是替换

f_score[something]

f_score.find(something)->second

这适用于const引用,因为在找不到something时它不会创建新元素。您应该检查是否实际找到了该元素:

map<Point, int>::const_iterator it = f_score.find(something);
if (it != f_score.end()) {
    // ok, something was found
} else {
    // element not found
}