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

Twice the same for loop: one compiles, the other does not

本文关键字:编译 一个 另一个 for 两次 循环      更新时间:2023-10-16

我有这段代码可以使几个字符串小写(请参阅此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);
}

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

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

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

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