0

For some reason, I am having trouble editing values in my unordered_map, and am wondering what I'm doing wrong.

In the following code, parameteris a struct. For some reason, the following code is throwing a syntax error, not liking the [.

void MyClass::setParameter(string name, parameter param) {
    if (this->param_name_to_data == nullptr) {
        //create it lazily
        this->param_name_to_data = new unordered_map<string, parameter>();
    }
    this->param_name_to_data->[name] = param;
}

The dictionary id declared in the corresponding .h file as:

private:
 std::unordered_map<std::string, parameter> * param_name_to_data = nullptr;

What am I doing wrong?

2
  • 2
    Is there some reason why you dynamically allocate the unordered_map? Commented Apr 3, 2016 at 22:04
  • I'll probably switch it to statically allocated. Commented Apr 3, 2016 at 22:05

1 Answer 1

4

param_name_to_data->[name] = param; is not a valid syntax

when the compiler sees -> it looks for either a member variable or a member function. the statement ->[...] is meaningless since [] alone is neither a member variable nor a function.

you can write instead

(*param_name_to_data)[name] = param;

or turn the pointer to reference first

auto& map = *param_name_to_data;
map[name] = param;

you can also use the ugly literal form of

param_name_to_data->operator[] (name) = param

but the last one is discouraged.

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

4 Comments

I had thought I had seen ->[] somewhere in code before, which is why I was trying to use it. Is there a reason why it's forbidden?
Thanks. I still find it weird that it is unable to intelligently search for any other operator's abbreviation. It's not a big deal, I'm just legitimately curious if there's some syntax-tree-ambiguity related reason or something that the compiler can't do that step.
it's basically like that because the standard didn't state that ->[] is a valid syntax for calling operator [] from a pointer. so no compiler implemented it. if the standard stated clearly that it should be valid, it would be correct
@user650261: "* I still find it weird that it is unable to intelligently search for any other operator's abbreviation.*" That's because it's not an "abbreviation". operator[] is the function's name. The -> operator is grammatically intended to be followed by a member name of the type returned by operator->. [] is not a member name, so it fails.

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.