gpt4 book ai didi

c++ - switch case 中 map 迭代器的交叉初始化

转载 作者:行者123 更新时间:2023-11-30 01:43:58 26 4
gpt4 key购买 nike

最近我在尝试一个使用 std::map 的程序,遇到了我需要在 switch case 中使用 map iterator 的情况。我的程序是这样的:-

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;


int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
map<string,int> m;
//map<string,int>::iterator itr;
int q, mark, type;
string name;
cin >> q;
while (q--)
{
cin >> type;
switch (type)
{
case 1: cin >> name >> mark;
m[name] += mark;
break;
case 2: cin >> name;
m.erase(name);
break;
case 3: cin >> name;
auto itr = m.find(name);
if (itr != m.end())
cout << itr->second << '\n';
else
cout << "0";
break; // problem lies here
default: cout << "ERROR !!!\n"; break;
}
}
return 0;
}

对于这段代码,我的编译器闪现了一个错误:-

Error] crosses initialization of 'std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, int> > itr'

如果我在 switch case 之外声明 iterator itr,则代码可以正确编译。谁能告诉我这个方法有什么问题???

最佳答案

你应该考虑在 C 和 C++ 中,一个 switch 是基于 goto 实现的,你不允许 goto 跳过初始化一个对象。

只需将每个 case 包装在一个 block { ... } 中,一切都应该没问题。产生问题的案例是带有 itr 的案例。

switch (type) 
{
case 1: {
cin >> name >> mark;
m[name] += mark;
break;
}
...
case 3: {
cin >> name;
auto itr = m.find(name);
...
break;
}
...
}

关于c++ - switch case 中 map 迭代器的交叉初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36969210/

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