[英]How can I access the elements of a pointer-to-map?
我已通过指向函数的指针传递了地图,但现在由于代码无法编译,因此无法更改地图的内容。 我不确定是否甚至允许我将地图作为指针传递。 例如:
#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;
}
}
当我编译这个我得到错误:
error: no match for ‘operator*’ (operand type is ‘std::map >’) *baa[1] = "somethingnew";
有可能像faa这样的功能吗? 语法是什么?
由于运算符优先级规则, *baa[1]
被解析为*(baa[1])
而不是(*baa)[1]
。 您可以在括号中加上使其生效。 但是,最好使用引用代替:
void faa(map<int,string> &baa){
baa[1] = "somethingnew";
}
然后,您只需调用该函数,而无需获取地图的地址:
faa(bar);
您可以改用(*baa)[1]
。
默认优先级与您写*(baa[1])
解释错误消息:如果baa
是指针,则可以使用[]
运算符访问指针指向的第n个元素,因此baa[1]
的类型为std::map
,并且没有*运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.