首页 > 解决方案 > 找到一种方法将匹配的键和值从映射推回向量

问题描述

我在 Java 中有与此类似的代码,但让它在 C++ 中工作是另一回事。目前,此功能确实正确找到了密钥并将密钥推到我的向量后面。我想抓住键和它的一对值都被插入到向量的同一个索引中。我已经研究过使用一对作为我的向量,所以它会是(键,一对值),我不确定我是否能够做到。

vector<string> getIfPresentPartOfSpeech(multimap<string, pair<string, string>> dictionary, string name) {
    vector<string> response;
    auto it = dictionary.begin();
    while (it != dictionary.end()) {
        // Check if value of this entry matches with given value
        if (it->second.first == name) {
            // Yes found
            // Push the key in given map
            response.push_back(it->first);
        }
        // Go to next entry in map
        it++;
    }
    return response;
}

标签: c++dictionaryvector

解决方案


为您定义一个结构response并返回std::vector该类型的一个。

struct Response {
  std::string key;
  std::pair<std::string, std::string> resp_pair;
};

vector<Response> getIfPresentPartOfSpeech(multimap<string, pair<string, string>> dictionary, string name) {
    vector<Response> response;
    auto it = dictionary.begin();
    while (it != dictionary.end()) {
        // Check if value of this entry matches with given value
        if (it->second.first == name) {
            // Yes found
            // Create a Response object
            Response resp;
            resp.key = it->first;
            resp.resp_pair = it->second;
            // Push it in the vector
            response.push_back(resp);
        }
        // Go to next entry in map
        it++;
    }
    return response;
}

通过使用emplace_back而不是push_back避免容器元素的多个副本传递来进一步优化这一点是可能的。


推荐阅读