C++ 不正确地使用指针/引用?
我有多个地图和指向地图的指针向量:C++ 不正确地使用指针/引用?,c++,pointers,reference,C++,Pointers,Reference,我有多个地图和指向地图的指针向量: map<string, int> one4, one5, one7 ; vector< map<string, int>*> Maps{ &one4, &one5, &one7 } ; 使用make命令编译时,我得到以下错误: error: request for member ‘count’ in ‘x’, which is of pointer type ‘std::map<std::__
map<string, int> one4, one5, one7 ;
vector< map<string, int>*> Maps{ &one4, &one5, &one7 } ;
使用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 ‘->’ ?)
错误:请求“x”中的成员“count”,该成员的指针类型为“std::map*”(可能您想使用“->”?)
我想我一定是用错了,但我不知道怎么用。我没有在C++中编码很多,所以请不要苛刻!p> 访问指针变量的成员函数时,必须使用箭头运算符,也称为间接成员选择运算符 以您的例子:
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 '.'
}
std::map one4{},one5{},one7{};
向量映射{&one4,&one5,&one7};
用于(标准::贴图*x:贴图){
标准::cout count(“映射键”)仔细阅读错误消息,它会告诉你该怎么做。也许你想使用“->”?
x->count
和->
是让程序员知道他们在处理什么的语言怪癖:引用或指针。通常对于指针变量,是的。你也可能在下一行遇到问题l、 (*x).count(…)
和(*x)[…]
应该可以。为什么还有一个指向映射的指针容器?映射的生存期是否与向量不同?是否需要?
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 ‘->’ ?)
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 '.'
}