我有一個舊地圖樣本:
map<string, int> map_ = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}
和一個鍵串列:
vector<string> list_ = {"B", "D", "E"}
我想根據密鑰串列從舊地圖中獲取新地圖:
map<string, int> mapNew_ = {"B": 2, "D": 4, "E": 5}
有什么聰明的方法可以做到這一點嗎?
uj5u.com熱心網友回復:
您可以使用基于范圍的簡單 for 回圈來完成此操作。那看起來像
map<string, int> mapNew_;
for (const auto& e : list_)
mapNew_[e] = map_[e];
如果list_可以包含不在地圖中的元素,那么您需要添加一個檢查,例如
map<string, int> mapNew_;
for (const auto& e : list_)
if (auto it = map.find(e); it != map.end())
mapNew_[e] = it->second; // no map_[e] here since it already points to the needed value
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465154.html
