【问题标题】:How to insert custom class item to map C++如何插入自定义类项以映射 C++
【发布时间】:2012-06-05 19:09:28
【问题描述】:

我有一个类,如何将这个类的一个对象添加到映射中,并通过 id 找到它?

类代码:

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?
}

我尝试了很多示例代码,但没有使用自定义类,因此它们不起作用。 谢谢!

【问题讨论】:

标签: c++ map iterator


【解决方案1】:

添加Client key=10:

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

查找 key=10 的元素:

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

你也可以使用:

Client c = ClientTable[10];

但调用operator[] 不是const。所以,如果你只想找到一个元素,那很可能不是你想要使用的。

【讨论】:

    【解决方案2】:

    1) "如何将此类的一个对象添加到地图中?"

    ClientTable[id] = c;
    

    嗯,从技术上讲,它会将对象的副本添加到地图中。

    2) "并通过 id 找到它?"

    Client lookerUpper = ClientTable[id];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 2019-01-21
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多