C++ 在映射的映射中循环时使用范围变量作为函数参数
我试图循环遍历一个映射映射,并将每对映射传递给一个修改内容的函数。当我试图编译下面的代码时,我得到了关于C++ 在映射的映射中循环时使用范围变量作为函数参数,c++,for-loop,reference,stdmap,C++,For Loop,Reference,Stdmap,我试图循环遍历一个映射映射,并将每对映射传递给一个修改内容的函数。当我试图编译下面的代码时,我得到了关于项范围变量声明的以下错误: error: invalid initialization of non-const reference of type 'std::pair<std::__cxx11::basic_string<char>, std::map<std::__cxx11::basic_string<char>, int> >&
项
范围变量声明的以下错误:
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)
incrementAndPrintIt()
的参数也应调整为相同的值
使用auto
很容易,首先可以避免整个头痛问题:
for(auto& index : names)
但是这对incrementAndPrintIt()
的参数没有帮助。但是,它不需要地图键,因此您只需将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;
}
#包括
#包括
#包括
void incrementAndPrintIt(标准::映射和值)
{
用于(自动和j:值){
j、 秒=j.秒+1;
标准::cout
for(std::pair<const std::string, std::map<std::string, int>>& index : names)
for(auto& index : names)
#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;
}