我有一个地图和一个矢量,我想通过从矢量中获取与地图中的钥匙对应的值来创建地图。我该怎么办?
我猜是这样的:
#include <iostream>
#include <map>
#include <vector>
int main()
{
std::map<int,int> dummy;
dummy.insert(std::pair<int,int>(1, 40));
dummy.insert(std::pair<int,int>(2, 30));
dummy.insert(std::pair<int,int>(3, 60));
dummy.insert(std::pair<int,int>(4, 20));
dummy.insert(std::pair<int,int>(5, 50));
std::vector<int>v{1,3,5};
std::map<int,int> final; // Final map
for(auto&e:v)
final[e]=dummy[e]; // Set key from vector, get value from dummy.
for(auto it = final.cbegin(); it != final.cend(); ++it)
{
std::cout << it->first << " " << it->second << "\n";
}
}
据我了解的问题,您想要这样的东西。我创建它作为最小的示例。希望我能正确理解您的问题:
#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
}