I have this error described in the title with one of my functions. From what I've read, a "passing XXX as 'this'
" error occurs when we try to pass a constant variable in a non-constant parameter. The thing is that the function causing it is from the std, and my compiler (g++ Ubuntu 11.0.0-19ubuntu1
, with -std=c++20
) seems to fail to choose the right override.
The errors occurs when calling this function :
double Matrix::sum(const CityList cities) const{
double res=0;
for(size_t i=0; i<cities.size()-1; i++)
res+=values[citiesIndex[cities[i]]][citiesIndex[cities[i+1]]];
return res+values[citiesIndex[cities.back()]][citiesIndex[cities.front()]];
}
It basically returns the total weight of the path taken by reaching the cities present in CityList aka std::vector<std::string> cities
, in order and back (I'm working on graphs). For example matrix.sum({"London","Paris","Madrid"};
will return the distance from London to Paris, plus from Paris to Madrid, plus from Madrid to London.
Matrix
is a class with members:
std::vector<std::vector<double>> values
the cells of the Matrix containing the weight of each egde of the graph
std::map<std::string,size_t> citiesIndex
is used to find the right rows and columns from a std::string
(the name of the city).
When compiling, I get an error message like :
passing 'const std::map<std::__cxx11::basic_string<char>, long unsigned int>' as 'this' argument discards qualifiers
,
and as a note it shows:
in call to ...
492| operator[](const key_type& __k)
I think it's the [] operator of std::map
that should be called as operator[](const key_type& __k) const
instead, but how can I force the compiler to use this one ? I'm sure it's a synthax problem and I'm not using things like they are intended to.
This error message is shown four times, pointing :
...citiesIndex[...]...
^
At the moment, the fix I made was to make the instance of Matrix non-constant (declaring double Matrix::sum(const CityList cities);
), but I really don't like this solution, and I would like to know how I could make the instance constant without errors, and what I've done wrong. Thanks.
EDIT
Just use citiesIndex.at(...)
instead of citiesIndex[...]