C++ 使用 std::vector 或 std::map 制作黑名单

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

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

以下是 "BanList" 是如何构建在 Networking.h 上的:

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

这是我的 Networking.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然后将目标添加到列表中......现在已经谢谢你的帮助。

仔细阅读 std::vector 的模板参数。 std::string 不是 int 的有效分配器 :)

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

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

从 reference/your 最喜欢的书中学习关于 std::vector/std::pairstd::map 的其余部分。不值得在这里解释(而且没有足够的space)。

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

我不太确定你的问题是什么。如果您想知道如何使用地图,那么您应该查看 the online reference.

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

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

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

对于一个矢量,你不能有 key/value 对,除非你推一个 std::pair 对象。尽管如此,您几乎总是会想要使用地图。

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

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