Linux GCC 中的 unordered_map 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7359284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:05:36  来源:igfitidea点击:

unordered_map error in GCC

c++linuxgcc

提问by station

When was the unordered_mapconcept built into g++?

这个unordered_map概念是什么时候内置到 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

无效类型 int[char[ 为 aaray 下标

What is the fix for this?

有什么办法解决这个问题?

采纳答案by mkaes

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:

问题是你的任务。您无法在此位置为您的地图赋值。C++ 不是脚本语言。
这个程序在我的机器上使用 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'];
}

回答by Diego Sevilla

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

首先,正如 mkaes 指出的,你不能把赋值放在函数之外,所以你必须把它放在 any 中,例如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:

至于unordered_map最近版本的gcc,如果不想进入C++11,可以使用TR1版本的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.

和类型std::tr1::unordered_map。你知道,C++11 取代了这一切,但你会(至少在 GCC 中)让它工作。