Home > Back-end >  Unknown type name error when inserting into unordered_map
Unknown type name error when inserting into unordered_map

Time:11-01

I have a single file called main.cpp where I am trying to declare an unordered_map as shown below.

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

I then try to insert a new (key, value) pair into the map as follows.

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

When I do this I get the following compiler error.

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;

So it seems to think I am declaring 'firstSets' when I am actually tring to insert into it. And it seems to treat 'firstSets' as an array instead of an unordered_map. How do I fix this?

CodePudding user response:

I don't know why it is not working, but you don't need to call make_pair... Changing the insertion line to:

firstSets.insert({decl, declFirstSet});

Should solve your problem.

Here would be a full code example:

#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 });   
}

But seems like you want them declared in global scope, so you would initialize like the following code:

#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()
{
}

CodePudding user response:

Your std::make_pair is wrong. To get closer you need a std::set<int> instead of the std::set.

But what you really want is to just let to compiler make it for you:

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

or use an easier syntax:

    firstSets[decl] = declFirstSet;

EDIT AFTER UNDERSTANDING THE PROBLEM On the otherhand, you want firstSets to come with initial content you can reorder the declarations:

#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() {}
  • Related