0

I have this:

unordered_map<string,string>* createDict(){

    unordered_map<string,string>* Dict= new unordered_map<string,string>();

    Dict["x"] = "a";
    Dict["y"] = "b";
    Dict["z"] = "c";

    return Dict;
}

and I get the error:

expression must have integral or unscoped enum type

but this works when allocating on the stack. What is the easiest way to solve this? I really dont like having to create Pair objects to insert in to an unordered_map.

6
  • 1
    Why not have the function return an unordered_map instead of a pointer to one? Commented Sep 20, 2013 at 22:10
  • @us2012 I must be honest I was going to do that, but this is going to be a data member of a class. Commented Sep 20, 2013 at 22:11
  • 1
    @user997112 Why does being a class' data member make it necessary to dynamically allocate the map? Commented Sep 20, 2013 at 22:13
  • @Praetorian stackoverflow.com/questions/18926689/… Commented Sep 20, 2013 at 22:18
  • @user I'm wondering whether you might have some misconceptions about what it means to have an object member variable vs a pointer member variable in a class A. You do not need a pointer member variable just because you want to dynamically allocate objects of type A! Commented Sep 20, 2013 at 22:32

2 Answers 2

4

Dict is a pointer to an std::unordered_map<std::string, std::string> but you are using it as if it is an object. You need to dereference the object appropriately, e.g., using

(*Dict)["x"] = "a";
Dict->operator[]("y") = "b";
std::unordered_map<std::string, std::string>& ref = *Dict;
ref["z"] = "c";

I'd prefer the first option or use

Dict->insert(std::make_pair("x", "a"));

Which has, however, slightly different semantics: if the key exists, it doesn't do anything while using the subscript operator and assignment would update the value.

Sign up to request clarification or add additional context in comments.

Comments

1

What is the easiest way to solve this?

Use universal initialization and just return the unordered_map rather than a pointer:

#include <unordered_map>
#include <string>

std::unordered_map<std::string, std::string> createDict(){
    return {{"x", "a"}, {"y", "b"}, {"z", "c"}};
}

int main() {
  auto xyz_dict = createDict();
}

Edit: Based on your comment that this data structure will be a member variable of some class, you could just initialize it in class:

struct A {
  using xyzDict = std::unordered_map<std::string, std::string>;
  xyzDict xyz_dict{{"x", "a"}, {"y", "b"}, {"z", "c"}};   
};

If your compiler doesn't support this, then just initialize xyz_dict with createDict() in the constructor's member initialization list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.