gpt4 book ai didi

c++ - 循环遍历 map 时使用范围变量作为函数参数

转载 作者:行者123 更新时间:2023-12-01 14:48:45 24 4
gpt4 key购买 nike

我正在尝试遍历 map 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++ - 循环遍历 map 时使用范围变量作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60272794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com