Why does using iterators work this way?

Here is the minimal code to recreate a condition that makes me doubt:

#include <map>
#include <string>

int main()
{
  std::map<std::string, std::string> mm;

  mm.emplace("Hi", "asd");
  mm.emplace("Hey", "asd");
  mm.emplace("Hello", "asd");

  std::map<std::string, std::string>::const_iterator it = mm.find("Hey");
  it->second.size();

  // A
  //it->second.replace(0,1,"h");

  //B
  auto u = it->second;
  u.replace(0,1,"h");
}

Why does the error of passing a constant occur as an argument in the case A, but it works in the case B?

Error Details:

error: 'const std:: basic_string' 'this''std:: basic_string < _CharT, _Traits, _Alloc > & :: basic_string < _CharT, _Traits, _Alloc > :: (:: basic_string < _CharT, _Traits, _Alloc > :: size_type, :: basic_string < _CharT, _Traits, _Alloc > :: size_type, Const _CharT *) [ _CharT = char; _Traits = std:: char_traits; _Alloc = std:: allocator; std:: basic_string < _CharT, _Traits, _Alloc > :: size_type = long unsigned int] ' [-fpermissive]

+4
1

: it - const, it->second - const std::string, .

:

auto u = it->second;

auto std::string, u it->second. u std::string, const, const-.

+11

Source: https://habr.com/ru/post/1681788/


All Articles