-2

I have a class, how can i add one object of this class to map, and find it by id?

Class code:

class Client {
    int FileDescriptor, Id, cryptcode;
    unsigned char CustomData[256];

    void PrepareClient()
    {
        // init code
    }
  public:
    AnticheatClient (int fd, int id, int crypt_code)
    {
        FileDescriptor = fd;
        Id = id;
        cryptcode = crypt_code;
        PrepareCrypt();
    }

    void OwnCryptEncrypt(unsigned char* data, int len)
    {
 //...
    }

    void OwnCryptDecrypt(unsigned char* data, int len)
    {
 //...
    }
};

std::map<int, Client> ClientTable;

int main()
{
 int id = 1;
 Client c(1, id, 1);
 // how can i add this client to map and how can i find it by id?
}

I tried so many example codes but not with custom class so they didn't work. Thanks!

bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • What do you mean by "they didn't work"? – Oliver Charlesworth Jun 05 '12 at 19:10
  • 1
    [StackOverflow is not a Language Tutorial.](http://meta.stackexchange.com/a/134609/142865) For good, peer-reviewed learning resources, check out [The Definitive C++ Book Guide and List](http://stackoverflow.com/q/388242/241536) and our [C++-FAQ Tag](http://stackoverflow.com/questions/tagged/c%2b%2b-faq) – John Dibling Jun 06 '12 at 18:14
  • Please copy-paste your error message. Also your attempted code in main. – qqqqq Sep 21 '15 at 20:32

2 Answers2

1

For adding a Client with key=10:

ClientTable[10] = Client(1, id, 1);

For find an element with key=10:

std::map<int, Client>::iterator it = ClientTable.find(10);
if (it != ClientTable.end()) {
    int key = it->first;
    Client c = it->second;
}

You can also use:

Client c = ClientTable[10];

but calling operator[] is not const. So, that is most probably not what you want to use if you just want to find an element.

betabandido
  • 18,946
  • 11
  • 62
  • 76
0

1) "how can i add one object of this class to map?"

ClientTable[id] = c;

Well, technically, it adds a copy of the object to the map.

2) "and find it by id?"

Client lookerUpper = ClientTable[id];
Robᵩ
  • 163,533
  • 20
  • 239
  • 308