插入 unordered_map 时出现未知类型名称错误

Unknown type name error when inserting into unordered_map

我有一个名为 main.cpp 的文件,我试图在其中声明一个 unordered_map,如下所示。

std::unordered_map<std::string, std::set<int>> firstSets;

然后我尝试将一个新的(键,值)对插入到映射中,如下所示。

std::string decl = "decl";
std::set<int> declFirstSet = {VOID_TOK, INT_TOK, FLOAT_TOK, BOOL_TOK};
firstSets[decl] = declFirstSet;

执行此操作时出现以下编译器错误。

C++ requires a type specifier for all declarations

firstSets[decl] = declFirstSet;

size of array has non-integer type 'std::string' (aka 'basic_string')

firstSets[decl] = declFirstSet;

所以它似乎认为我在声明 'firstSets' 时我实际上是想插入它。而且它似乎将 'firstSets' 视为数组而不是 unordered_map。我该如何解决这个问题?

我不知道为什么它不起作用,但你不需要调用 make_pair... 将插入行更改为:

firstSets.insert({decl, declFirstSet});

应该可以解决你的问题。

这是一个完整的代码示例:

#include <set>
#include<string>
#include <unordered_map>
using namespace std;
int main()
{
    std::unordered_map<std::string, std::set<int>> firstSets;
    set<int> s = { 1, 2, 3 };
    firstSets.insert({ "key", s });   
}

但是您似乎希望它们在全局范围内声明,因此您可以像下面的代码一样进行初始化:

#include <set>
#include<string>
#include <unordered_map>
using namespace std;

set<int> s1 = { 1, 2, 3 }, s2 = { 4, 5, 6 };
std::unordered_map<std::string, std::set<int>> firstSets{ {"key1", s1}, {"key2", s2}};
int main()
{
}

你的std::make_pair错了。为了更接近你需要一个 std::set<int> 而不是 std::set.

但您真正想要的是让编译器为您完成:

    firstSets.insert(std::make_pair(decl, declFirstSet));

或使用更简单的语法:

    firstSets[decl] = declFirstSet;

了解问题后编辑 另一方面,您希望 firstSets 带有初始内容,您可以重新排序声明:

#include <set>
#include <string>
#include <unordered_map>

std::string decl{"decl"};
std::set<int> declFirstSet{1, 2, 3, 4};
std::unordered_map<std::string, std::set<int>> firstSets{{decl, declFirstSet}};

int main() {}