找到一种方法将push_back匹配的地图中的键和值匹配到矢量中


猫南北
2025-03-08 01:56:05 (13天前)
  1. 我在Java中使用的代码与此类似,但在C ++中使用它是一个不同的故事。目前,此功能确实正确找到了密钥,并将密钥推送到我的矢量背面。一世 ...

2 条回复
  1. 0# 易米烊光 | 2019-08-31 10-32



    您可以使用

    std::copy_if





    无需手动编写显式循环。也过去了

    dictionary

    通过(常量)引用来避免不必要的复制:



    1.   #include <algorithm>
    2. include

      include

      include

      // You’ll need C++14 to use auto const& kv in your lambda expression
      std::vector>>
      getIfPresentPartOfSpeech(
      const std::multimap>&
      dictionary,
      const std::string& name)
      {
      std::vector<
      std::pair>>
      res;
      std::copy_if(begin(dictionary), end(dictionary), std::back_inserter(res),
      & { return kv.second.first == name; });
      return res;
      }

    3. //test
      int main()
      {
      std::multimap> dictionary{
      {“first”, {“abc”, def”}},
      {“second”, {“123”, 456”}},
      {“first”, {“asdf”, fdas”}},
      {“thrid”, {“abc”, 123”}},
      };
      auto res = getIfPresentPartOfSpeech(dictionary, abc”);
      for (auto& x : res)
      std::cout << x.first << << x.second.first << << x.second.second
      << \n”;
      }

    4. </code>


    使用像@aep这样的结构会更加清晰。你需要一个额外的转换构造函数才能使用它

    std::copy_if





    1. struct Response {
      std::string key;
      std::pair value;
      // Provide a conversion constructor that convert your dictionary multimap
      // key-value pair into a Response object
      Response(const std::pair>& kv)
      : key{kv.first}, value{kv.second}
      {}
      };

    2. std::vector getIfPresentPartOfSpeech(
      const std::multimap>&
      dictionary,
      const std::string& name)
      {
      std::vector res;
      std::copy_if(begin(dictionary), end(dictionary), std::back_inserter(res),
      & { return kv.second.first == name; });
      return res;
      }

    3. </code>

登录 后才能参与评论