[英]cross initialization of map iterator in a switch case
最近,我正在嘗試使用std::map
的程序,並遇到需要在開關盒中使用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 ++中基於goto
實現switch
,並且不允許goto
跳過對象的初始化。
只需將每個case
包裝在一個塊{ ... }
,一切就可以了。 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.