0

I'm starting with C++ and I'm trying to expand std::map class via composition. I want to use this class CardPackage to have a private map of ids and pointers to my EntityCards and implement three methods AddCard, GetCard and RemoveCard that will access the private map m.

The issue is that I have not been able to work with m methods (find and end) because I get the following error message:

expression must have a pointer type

I understand that m needs to be a pointer to be accessed by arrow notation (or dot) but I can't figure out to adapt the code to respect my requirements.

Header:

#include <EntityCard.h>

class CardPackage
{
public:

CardPackage();
~CardPackage();

void AddCard(EntityCard* card);
EntityCard* GetCard(int id);
bool RemoveCard(int id);

private:
    map<int, EntityCard*> m;
};

Source:

#include "CardPackage.h"

CardPackage::CardPackage()
{
}


CardPackage::~CardPackage()
{
}

   void CardPackage::AddCard(EntityCard *card)
   {
        m[card->ID] = card;
   }

EntityCard* CardPackage::GetCard(int id)
{
    if (id < 1) { return nullptr; }
    if(m->find(id) == m->end())
    {
        return (m[id]);
    }
    else
    {
        return nullptr;
    }
}

bool CardPackage::RemoveCard(int id)
{
    //TODO
    return false;
}
Sturm
  • 3,968
  • 10
  • 48
  • 78

1 Answers1

5
   if(m->find(id) == m->end())

Should be:

   if(m.find(id) != m.end())

m is not a pointer, so you need ., rather than ->. You also have the test the wrong way round.

A slightly better implementation would be:

   const auto it = m.find(id);
   if (it != m.end())
       return it->second;
   else
       return nullptr;

The difference is that this only does one lookup in the map, whereas your code does two.

  • I wrongly assumed . (dot) and -> (arrow) were the same. http://stackoverflow.com/questions/1238613/what-is-the-difference-between-the-dot-operator-and-in-c – Sturm Feb 21 '17 at 12:16
  • 1
    @Sturm they are not. Usually only `->` or `.` can be applied depending on whether you apply it to a pointer or an object. However, there are some "hybrid" types that implement both (e.g. smartpointers) – 463035818_is_not_an_ai Feb 21 '17 at 12:19
  • @Martin wouldn't it be `return it->second;` ? I get an error if I just return *it – Sturm Feb 21 '17 at 12:23