c++ - 在循环映射映射时使用范围变量作为函数参数

标签 c++ for-loop reference stdmap

我正在尝试循环遍历 map 并将每一对传递给修改内容的函数。当我尝试编译以下代码时,出现关于 item 范围变量声明的以下错误:

error: invalid initialization of non-const reference of type 'std::pair<std::__cxx11::basic_string<char>, std::map<std::__cxx11::basic_string<char>, int> >&' from an rvalue of type 'std::pair<std::__cxx11::basic_string<char>, std::map<std::__cxx11::basic_string<char>, int> >'
     for(std::pair<std::string, std::map<std::string, int>>& index : names)

当我尝试使用 auto& 声明范围变量索引时,错误从范围变量声明转移到函数调用 incrementAndPrintIt(index);

#include <iostream>
#include <vector>
#include <map>

void incrementAndPrintIt(std::pair<std::string, std::map<std::string, int>>& value)
{
    for(auto& j : value.second) {
        j.second = j.second + 1;
        std::cout << "j:  " << j.second << std::endl;
    }
}

int main() {

    //initialize a map of maps
    std::map<std::string, std::map<std::string, int>> names = {{"women",{{"Rita",2}}},{"men",{{"Jack",4}}}};

    for(std::pair<std::string, std::map<std::string, int>>& index : names) {
        incrementAndPrintIt(index);
    }
    return 0;
}  

最佳答案

 for(std::pair<std::string, std::map<std::string, int>>& index : names) 

std::map 中,映射的键(对中的第一个值)是一个常量值。

这应该是:

 for(std::pair<const std::string, std::map<std::string, int>>& index : names) 

incrementAndPrintIt()的参数也应该调整为相同。

使用 auto 可以轻松地从一开始就避免整个令人头疼的问题:

 for(auto& index : names) 

但这对 incrementAndPrintIt() 的参数没有帮助。但是它不需要 map 的键,因此您只需将 index.second 传递给它即可,从而避免键盘上的大量磨损:

#include <iostream>
#include <vector>
#include <map>

void incrementAndPrintIt(std::map<std::string, int> &value)
{
    for(auto& j : value) {
        j.second = j.second + 1;
        std::cout << "j:  " << j.second << std::endl;
    }
}

int main() {

    //initialize a map of maps
    std::map<std::string, std::map<std::string, int>> names = {{"women",{{"Rita",2}}},{"men",{{"Jack",4}}}};

    for(auto& index : names) {
        incrementAndPrintIt(index.second);
    }
    return 0;
}

您必须承认:这要简单得多,不是吗?

关于c++ - 在循环映射映射时使用范围变量作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60272794/

相关文章:

c++ - Cocos2D-X v3.0 Final 中的对象池 - 弃用 CCArray

c++ - 检查 map 中的 map 中是否存在元素

javascript - 如何移动到下一个 td 并检查 Css 类?

javascript - For循环性能: storing array length in a variable

arrays - 如何通过哈希值之一从哈希数组中获取哈希引用?

c# - 将 QT/C++ 转换为 C#

c++ - DirectX HLSL 着色器隐式截断 vector 类型错误

javascript - 我可以更改循环中使用的 ID 吗?需要在 6 次迭代中更改 1 个字符

c++ - std::cout 改变变量值

c++ - 何时使用变量/引用参数作为输出?