Error “xxxx”does not name a type

前端 未结 3 2089
花落未央
花落未央 2021-02-20 01:47

I encountered a problem when tried compiling the following code:

#include 
#include 
#include 
#include 

        
相关标签:
3条回答
  • 2021-02-20 02:09

    You can't have statements like mapDial['A'] = 2; at global scope. They must be inside a function.

    0 讨论(0)
  • 2021-02-20 02:18

    When you declare a variable in global scope, you may only do initialization. E.g,

    int a = 0;
    

    You cannot do normal statements like:

    a = 9;
    

    So I would fix the code with:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <map>
    
    using namespace std;
    
    map<char, int> mapDial;
    
    int main()
    {
      mapDial['A'] = 2;
      cout << mapDial['A'] << endl;
      return 0;
    }
    
    0 讨论(0)
  • 2021-02-20 02:25

    You cannot execute arbitrary expressions at global scope, so

    mapDial['A'] = 2;
    

    is illegal. If you have C++11, you can do

    map<char, int> mapDial {
        { 'A', 2 }
    };
    

    But if you don't, you'll have to call an initialisation function from main to set it up the way you want it. You can also look into the constructor of map that takes an iterator, and use that with an array in a function to initialise the map, e.g.

    map<char, int> initMap() {
        static std::pair<char, int> data[] = {
            std::pair<char, int>('A', 2)
        };
    
        return map<char, int>(data, data + sizeof(data) / sizeof(*data));
    }
    
    map<char, int> mapDial = initMap();
    
    0 讨论(0)
提交回复
热议问题