1

I have this piece of code to make a couple of strings lower case (see this SO post).

void some_free_standing_function(std::string solver, std::map<std::string, option_t> opts) {

    for (auto & c : solver) c = tolower(c);
    for (auto p : opts)
        for (auto & c : p.first)
            c = tolower(c);
}

The first range-based for seems to compile, the last one does not: Clang gives me error: cannot assign to variable 'c' with const-qualified type 'const char &'.

Why does the first one pass but not the second one, given that they are exactly the same?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Nibor
  • 1,236
  • 9
  • 23
  • 3
    OT: if it would compile it would still be useless becaus you modify a copy of the original map. –  Jan 31 '18 at 09:41

1 Answers1

5

Note that the value_type of std::map is std::pair<const Key, T>, that means for p.first you'll get a const std::string, and then the type of c will be const char&, which can't be modified.

The 1st one code snippet doesn't have such issue; solver is a non-const std::string.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405