【问题标题】:C++ Make a banlist with std::vector or std::mapC++ 使用 std::vector 或 std::map 创建一个禁止列表
【发布时间】:2016-02-18 14:46:04
【问题描述】:

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

这是在 Networking.h 上构建“BanList”的方式:

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

这是我的 Networking.cpp 的 sn-p(目标被添加到禁止列表的位置)

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 并将目标添加到列表中......现在已经感谢您的帮助。

【问题讨论】:

    标签: c++ list dictionary vector std


    【解决方案1】:

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

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

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

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

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

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

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

    【讨论】:

      【解决方案2】:

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

      这将更接近std::map&lt;int, std::string&gt;:

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

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

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

      【讨论】:

      • 谢谢! :-) 这对我有帮助^-^
      猜你喜欢
      • 1970-01-01
      • 2020-03-23
      • 2012-03-12
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 2014-04-12
      • 1970-01-01
      相关资源
      最近更新 更多