Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unordered_map error in GCC

Tags:

c++

linux

gcc

When was the unordered_map concept built into g++?

Because the following code throws an error.

#include<iostream>
#include<unordered_map>
#include<stdio.h>

using namespace std;

std::unordered_map<std::int,int> mirror;

mirror['A'] = 'A';
mirror['B'] = '#';
mirror['E'] = 3;

int main(void)
{
    std::cout<<mirror['A'];
    std::cout<<mirror['B'];
    std::cout<<mirror['C'];
    return 0;
}

I am compiling the code as follows:

g++ -c hashexample.cpp
g++ -o result hashExample.o
./result

The error I got is this:

inavalid types int[char[ for aaray subscript

What is the fix for this?

like image 464
station Avatar asked Dec 27 '22 14:12

station


2 Answers

The problem is your assignment. You cannot assign values to your map in this place. C++ is not a script language.
This program works fine on my machine with gcc4.6:

#include<iostream>
#include<unordered_map>

std::unordered_map<int,int> mirror;

int main() {
    mirror['A'] = 'A';
    mirror['B'] = '#';
    mirror['E'] = 3;

    std::cout<<mirror['A'];
    std::cout<<mirror['B'];
    std::cout<<mirror['C'];
}
like image 89
mkaes Avatar answered Jan 05 '23 03:01

mkaes


First, as mkaes points out, you cannot put assignments outside functions, so you have to put it in any, for example main.

As for unordered_map, for recent versions of gcc, if you don't want to go into C++11, you can use the TR1 version of unordered_map:

#include <tr1/unordered_map>

and the type std::tr1::unordered_map. You know, C++11 supersedes all this, but you will (at least in GCC) get this working.

like image 24
Diego Sevilla Avatar answered Jan 05 '23 02:01

Diego Sevilla