c++ - 通过从向量中获取键和与映射中的键对应的值来创建映射
问题描述
我有一个地图和一个向量,我想通过从向量中获取与地图中的键对应的值来创建一个地图。我怎么做?
解决方案
据我了解你想要这样的问题。我创建它作为最小的例子。希望我正确理解了您的问题:
#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
}
推荐阅读
- javascript - 如何在 ReactJS 中使用数组来渲染表格?
- django - CSRF 令牌丢失或不正确 - Django 2.2
- c++ - 如何存储前一个“for”循环中的计数器++并在下一个循环中再次使用它?
- java - 在 JavaFx 应用程序中禁用 Windows 触摸反馈
- r - 带有宽文件的 R 彩色图
- angular - 如何设置子模块路由数据?
- r - 数学方程式的 Rmarkdown 图形标题
- r - 在 R 中使用双循环添加一列
- android - Android MVVM retrofit2 模型未更新
- linux - ldapwhoami 没有根据 tcpdump 发送流量