0

I've passed a map by pointer to a function, but now I'm unable to change the contents of the map because the code doesn't compile. I'm unsure whether I'm even allowed to pass the map as a pointer. For example:

#include <iostream>
#include <stdlib.h>
#include <map>
#include <string>
using namespace std;

void faa(map<int,string> *baa){
   *baa[1] = "somethingnew";
}

int main(){
    map<int,string> bar;
    bar[1] = "one";
    bar[2] = "two";
    bar[3] = "three";

    int ii;
    for(ii=1;ii<4;ii++){
        cout<<"bar["<<ii<<"]="<<bar[ii]<<endl;
    }

    faa(&bar);
    cout<<"after"<<endl;
    for(ii=1;ii<4;ii++){
        cout<<"bar["<<ii<<"]="<<bar[ii]<<endl;
    }
}

When I compile this I get the error:

error: no match for ‘operator*’ (operand type is ‘std::map >’)
     *baa[1] = "somethingnew";

Is a function like faa possible? What is the syntax?

3
  • 3
    (*baa)[1] should work instead Commented Aug 12, 2015 at 13:58
  • @ddriver doesn't have the same meaning WRT constness and what to do with unfound keys though. Commented Aug 12, 2015 at 14:06
  • 1
    @ddriver at and operator[] are semantically different if the key is not found. Commented Aug 12, 2015 at 14:06

2 Answers 2

8

Due to operator precedence rules, *baa[1] is parsed as *(baa[1]) instead of (*baa)[1]. You could just put in the parentheses to make it work. However, you'd be better off using references instead:

void faa(map<int,string> &baa){
   baa[1] = "somethingnew";
}

Then you just call the function without taking the address of the map:

faa(bar);
Sign up to request clarification or add additional context in comments.

1 Comment

Plus1 for pointing out use of reference. That is the way to go with STL containers in general.
2

You can use (*baa)[1] instead.

The default precedence is the same as if you wrote *(baa[1])

To explain the error message: if baa is a pointer, you can use the [] operator to access the nth element pointed by the pointer, therefore the type of baa[1] is an std::map, and it has no * operator.

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.