C++ 使用 std::vector 或 std::map 制作一个禁止列表

C++ Make a banlist with std::vector or std::map

本文关键字:std 禁止 列表 一个 vector 使用 map C++      更新时间:2023-10-16

我正在尝试用std::vector/std::map编写一个小的禁止列表。但我还不知道它应该如何工作...

以下是"BanList"在Networking.h上的构建方式:

static std::vector<int, std::string>BanList;
  • Int 代表 ID
  • 目标 IP 的字符串

这是我的网络片段.cpp(目标被添加到禁止列表中)

if (boost::contains(dataPackage.data, needle1) && boost::contains(dataPackage.data, needle2))
{
        // All okay here - Let's jump over & let the thread handle the action
}
else
{
    //e.g. BanList.addTarget(Auto-Incremented ID, TargetsIP);
    break;
}

所以在//的行上,例如 BanList.addTarget(int, string); 它应该如何与 std::vector 或 std::map 一起工作?现在如何创建包含目标的列表?获得IP不是我的问题!问题是如何自动设置 ID 并将目标添加到列表中......现在已经感谢您的帮助。

我不太确定你的问题是什么。如果您想知道如何使用地图,那么您应该看到在线参考。

在特定情况下,如果您使用地图:

static std::map<int, std::string> banList;
banList[id] = ipAddress;

我不知道你为什么要将整数映射到禁止列表的字符串。但这就是你的做法。

对于向量,除非推送std::pair对象,否则不能有键/值对。为此,您几乎总是希望使用地图。

要添加到矢量,请使用 vec.push_back(item)

您几乎可以在在线参考中找到所有这些。

小心地读取std::vector的模板参数。 std::string不是int :)的有效分配器

这将更接近std::map<int, std::string>

std::vector<std::pair<int, std::string>> BanList;

从参考/您最喜欢的书中了解有关std::vector/std::pairstd::map的其余信息。这里不值得解释(而且没有足够的空间)。

如果TargetsIP类似于 std::vector<std::string> ,则需要遍历它并将元素附加到循环中的BanList