Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "xxxx"does not name a type

Tags:

c++

types

I encountered a problem when tried compiling the following code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>

using namespace std;

map<char, int> mapDial;

mapDial['A'] = 2;

int main()
{

  cout << mapDial['A'] << endl;
  return 0;
}

The compiler gave me a error: 'mapDial' does not name a type error. I am new to c++ and really don't know what is going on here. Can anyone here help me to solve this? Thanks!!

like image 872
Lamian Avatar asked Oct 23 '12 22:10

Lamian


1 Answers

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();
like image 102
Seth Carnegie Avatar answered Oct 21 '22 08:10

Seth Carnegie