doncsoo
doncsoo

Reputation: 35

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?

Upvotes: 1

Views: 2533

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 30489

Instead of map_array_util(std::map<A,B> _m), you possibly meant

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.

Upvotes: 2

Jarod42
Jarod42

Reputation: 217135

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) {}

Upvotes: 4

Related Questions