【问题标题】:Twice the same for loop: one compiles, the other does not两次相同的 for 循环:一个编译,另一个不编译
【发布时间】:2018-01-31 09:29:46
【问题描述】:

我有这段代码可以将几个字符串变成小写(参见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);
}

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

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

【问题讨论】:

  • OT:如果它会编译它仍然没有用,因为你修改了原始地图的副本。

标签: c++ string c++11 dictionary


【解决方案1】:

请注意std::mapvalue_typestd::pair&lt;const Key, T&gt;,这意味着对于p.first,您将获得const std::string,然后c 的类型将是const char&amp;,无法修改。

第一个代码sn-p没有这个问题; solver 是一个非常量 std::string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2013-08-02
    • 2011-09-07
    • 1970-01-01
    相关资源
    最近更新 更多