1

i have a class which creates a tiled map, but i've got an error with the virtual void draw function :

    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
    {
        states.transform *= getTransform();

        for (int k = 0; k < m_layers ; ++k)
        {
            for (int i = minimum.x; i < maximum.x && i < m_width; ++i)
            {
                for (int j = minimum.y; j < maximum.y && j < m_height; ++j)
                {
                    target.draw(m_map[m_width*(j+k*m_height)+(i+k*m_width)].block, states);
                }
            }
        }
    }

And i've got this error :

error: passing 'const std::map<int, carte>' as 'this' argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = int; _Tp = carte; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, carte> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = carte; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]' discards qualifiers [-fpermissive]|

I have no idea how to fix this, can you help me please :(

If you wonder what "carte" means it's "map" in french. The carte struct has 3 members: an int (data), a sprite ("block") , and a bool (for collisions)

Sorry for my poor english.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
thp9
  • 376
  • 2
  • 15

2 Answers2

3

Your draw function is declared const. That means you are not allowed to change the object it is called upon. Your map is part of this object and therefore is not allowed to change either. Now you wonder what this means, because your map does not change, right? Well, the compiler does not know this. You are calling operator[] on your map and that is declared as non-const. In other words: you call a method on your map that can potentially change it and your compiler complains that you are not allowed to do so.

const sf::Drawable& d = m_map.at(m_width*(j+k*m_height)+(i+k*m_width)).block;
target.draw(d, states);

This will call a method on the map that is guaranteed to not change it.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
1

error: passing 'const std::map<int, carte>'

Seems like your map is const, hence you cannot use operator[] on it (see this question for example). You have two choices : remove the constness, or use the std::map::at method to access your elements.

Community
  • 1
  • 1