切换案例中映射迭代器的交叉初始化

Ank*_*rya 1 c++ iterator switch-statement

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Error] crosses initialization of 'std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, int> > itr'
Run Code Online (Sandbox Code Playgroud)

如果我声明iterator itr外部,switch case那么代码将正确编译。谁能告诉我这种方法有什么问题???

650*_*502 5

您应该考虑在 C 和 C++switch中实现基于goto并且不允许goto跳过对象的初始化。

只需将每个包裹case在一个块中{ ... },一切都应该没问题。造成问题的案例是itr.

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