簡體   English   中英

切換案例中地圖迭代器的交叉初始化

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM