[英]C++ Iterating through map from pointer
I want to iterate through a map, which address is stored in a pointer, so I can access and modify the original map, however whenever I try to iterate, it always gives me a read access violation. 我想遍历一个映射,该地址存储在一个指针中,因此我可以访问和修改原始映射,但是,每当我尝试进行迭代时,它总是会给我造成读取访问冲突。
#include <map>
template<typename A, typename B>
class map_array_util
{
public:
map_array_util(std::map<A,B> _m)
{
m = &_m;
}
void copy(B *arr, int size)
{
}
bool equals(B *arr, int size) const
{
int i = 0;
for (auto it = (*m).begin(); it != (*m).end(); ++it)
{
std::pair<A, B> p = *it;
if (*(arr + i) != p.second)
{
return false;
}
i++;
}
return true;
}
private:
std::map<A, B> *m;
};
How do we iterate in the correct way? 我们如何以正确的方式进行迭代?
You store address of local copy with 您将本地副本的地址存储在
map_array_util(std::map<A,B> _m)
{
m = &_m;
}
So you have dangling pointer. 因此,您有悬空的指针。
You probably want to pass by reference: 您可能希望通过引用传递:
map_array_util(std::map<A,B>& _m) : m(&_m) {}
Instead of map_array_util(std::map<A,B> _m)
, you possibly meant 代替
map_array_util(std::map<A,B> _m)
,您可能意味着
map_array_util(std::map<A,B> &_m)
// ^
BTW this class is not a good idea IMO. 顺便说一句,这不是国际海事组织的好主意。 You can better drive your class from a reference_wrapper.
您可以更好地从reference_wrapper驱动类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.