c++ - 从 Map 中获取 Value 中具有给定值的元素

标签 c++ dictionary

我有一个定义为 std::map<std::string, textInfo> tempMap; 的 map textInfo 类有一些属性为 textsize , textcolor , textfont ETC.. 我想从此 map 中选择一个与 textInfo 中属性的给定值匹配的项目类。

例如如果 map 包含

<"A",textInfo("10","Red","Verdana")>
<"B",textInfo("12","Green","Timesnewroman")>
<"C",textInfo("11","Blue","Cambria")>

我想选择在其 textfont 属性中包含“Cambria”的项目。 <"C",textInfo("11","Blue","Cambria")>

最佳答案

std::find_if应该可以满足您的需求。

示例程序:

#include <iostream>
#include <map>
#include <algorithm>

struct textInfo
{
   std::string textsize;
   std::string textcolor;
   std::string textfont;
};

int main()
{
   std::map<std::string, textInfo> m = 
   {
      {"A", {"10","Red","Verdana"}},
      {"B", {"12","Green","Timesnewroman"}},
      {"C", {"11","Blue","Cambria"}}
   };

   auto iter = std::find_if(m.begin(),
                            m.end(),
                            [](std::pair<std::string, textInfo> const& item)
                            { return (item.second.textfont == "Cambria");});
   if ( iter != m.end() )
   {
      auto& item = iter->second;
      std::cout << item.textsize << ", " << item.textcolor << ", " << item.textfont << std::endl;
   }
}

输出:

11, Blue, Cambria

关于c++ - 从 Map 中获取 Value 中具有给定值的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44150208/

相关文章:

c++ - 在 C++ 中创建大小为 1000000000 的数组给了我以下错误。请帮助我理解并解决它

c++ - rand 在不改变种子的情况下改变值(value)

c++ - STL 术语中的一对一关系

ios - 如何使用 plutil 编辑 .plist 文件中数组包含的字典的键值对

c++ - 在 Linux 中使用 GTK+ 调用带有按钮的对话框的库

c++ - 为什么英特尔编译器忽略英特尔 MIC 的非时间预取 pragma 指令?

python - 使用字典替换列表中的数字

python - 字典中的重复项(Python)

python - 合并两个共享相同键值的字典 :Value

c++ - 为什么在我的程序中调用了两次构造函数?