循环两次相同:一个编译,另一个不编译

Nib*_*bor 1 c++ string dictionary c++11

我有这段代码来制作几个字符串小写(请参阅此SO帖子).

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);
}
Run Code Online (Sandbox Code Playgroud)

第一个基于范围的for似乎是编译,最后一个不是:Clang给了我error: cannot assign to variable 'c' with const-qualified type 'const char &'.

为什么第一个通过但不通过第二个,因为它们完全相同?

son*_*yao 5

注意value_typestd::map就是std::pair<const Key, T>,这意味着对p.first你会得到一个const std::string,然后类型c将是const char&,它不能被修改.

第一个代码片段没有这样的问题; solver是一个非常数std::string.