c++ - 在遍历地图时使用范围变量作为函数参数
问题描述
我正在尝试遍历地图并将每一对传递给修改内容的函数。当我尝试编译以下代码时,我收到关于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)
在 astd::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;
}
您必须承认:这要简单得多,不是吗?
推荐阅读
- javascript - jQuery验证错误信息定位很奇怪
- c - c - 用空终止符覆盖换行符转义字符会导致段错误
- r - 查看路口附近的地块
- sql-server - SQL Server 动态 groupby 数据透视
- r - 如何应用于矩阵列表中第 j 个矩阵的每个第 i 列
- php - 获取通话状态 twilio php
- python - 在 Amazon Cognito MFA 中恢复
- haskell - 用 zipWith 写 zip
- angular - 无法读取未定义的属性“NullLogger”
- java - Connection with Java Spring, maven, oracle, hibernate