c++ - 错误地使用指针/引用?
问题描述
我有多个地图,以及指向地图的指针向量:
map<string, int> one4, one5, one7 ;
vector< map<string, int>*> Maps{ &one4, &one5, &one7 } ;
在某些功能中,我有一个我不确定是否正确的循环:
for( map<string, int>* x : Maps ) { }
我想直接访问各个地图并更改循环内的条目。例如,我写道:
if( !(x.count( binStr ))) {
x[ binStr ] = 1 ;
}
使用make
命令编译时,出现以下错误:
error: request for member ‘count’ in ‘x’, which is of pointer type ‘std::map<std::__cxx11::basic_string<char>, int>*’ (maybe you meant to use ‘->’ ?)
我想我必须使用 * 和 & 错误,但我不确定如何。我用 C++ 编写的代码不多,所以请不要苛刻!
解决方案
访问指针变量的成员函数时,必须使用箭头运算符,也称为间接成员选择运算符。
使用您的示例:
std::map<std::string, int> one4 {}, one5 {}, one7 {};
std::vector<std::map<std::string, int>*> Maps { &one4, &one5, &one7 };
for( std::map<std::string, int>* x : Maps) {
std::cout << x->count("Map Key") << std::endl;
// you can also do the following
// std::cout << (*x).count("Map Key") << std::endl;
// dereference the pointer and then apply the direct
// member selection operator '.'
}