首页 > 解决方案 > 通过从向量中获取键和与映射中的键对应的值来创建映射

问题描述

我有一个地图和一个向量,我想通过从向量中获取与地图中的键对应的值来创建一个地图。我怎么做?

标签: c++dictionaryvectorstl

解决方案


据我了解你想要这样的问题。我创建它作为最小的例子。希望我正确理解了您的问题:

#include <vector>
#include <map>
#include <string>

int main()
{
    // init example vector
    std::vector<std::string> keys;
    keys.push_back("key_1");
    keys.push_back("key_2");

    // ini example map
    std::map<std::string, std::string> someMap;
    someMap.insert(std::pair<std::string, std::string>("key_1", "val_1"));
    someMap.insert(std::pair<std::string, std::string>("key_3", "val_3"));

    // create new empty map for the results
    std::map<std::string, std::string> resultMap;

    // iterate over the vector an check keys against the map
    for(uint64_t i = 0; i < keys.size(); i++)
    {
        std::map<std::string, std::string>::const_iterator it;
        it = someMap.find(keys.at(i));

        // if key of the vector exist within the map, add the key with the value to the result map
        if(it != someMap.end())
        {
            resultMap.insert(std::pair<std::string, std::string>(it->first, it->second));
        }
    }

    // after this, the resultMap contains only "key_1" with "val_1", 
    // so only entries of the vector with the corresponding value within the map
}

推荐阅读