Reputation: 77
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?
Upvotes: 0
Views: 184
Reputation: 5855
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.
Upvotes: 2
Reputation: 65600
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);
Upvotes: 8