[英]cross initialization of map iterator in a switch case
Recently i was trying out a program using std::map
and came across a situation where I needed to use the map iterator
in a switch case. 最近,我正在尝试使用
std::map
的程序,并遇到需要在开关盒中使用map iterator
的情况。 My program goes like this :- 我的程序是这样的:
#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;
}
For this code my compiler flashes an error :- 对于此代码,我的编译器闪烁一个错误:
Error] crosses initialization of 'std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, int> > itr'
If I declare the iterator itr
outside the switch case
then the codee compiles properly. 如果我在
switch case
外声明了iterator itr
,则编解码器将正确编译。 Can anyone tell me what's wrong in this method ??? 谁能告诉我这种方法有什么问题吗?
You should consider that in C and C++ a switch
is implemented based on goto
and you are not allowed have a goto
skipping the initialization of an object. 您应该考虑在C和C ++中基于
goto
实现switch
,并且不允许goto
跳过对象的初始化。
Just wrap each case
in a block { ... }
and everything should be fine. 只需将每个
case
包装在一个块{ ... }
,一切就可以了。 The case creating the problem is the one with the itr
. itr
问题的案例就是itr
。
switch (type)
{
case 1: {
cin >> name >> mark;
m[name] += mark;
break;
}
...
case 3: {
cin >> name;
auto itr = m.find(name);
...
break;
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.