如何使用映射C中的值获取匹配键

前端之家收集整理的这篇文章主要介绍了如何使用映射C中的值获取匹配键前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个结构作为值类型的地图
  1. map<int id,struct_t*> table
  2.  
  3. struct_t
  4. {
  5. int prev;
  6. int wt;
  7. string name;
  8. }

仅使用prev,我需要找到相应的id.非常感谢提前!

编辑:

  1. int key=0;
  2. for(auto it = table.begin(); it != table.end(); ++it)
  3. {
  4. if(table[(*it).first].prev == ?)
  5. }

这就是我的地图数据的样子:

  1. id prev abundance thing
  2. 1573 -1 0 book
  3. 1864 1573 39 beds
  4. 2075 1864 41 tray
  5. 1760 2075 46 cups

对于每个id,我需要找到NEXT匹配id.因此,对于来自prev列的1573,我需要找到匹配的’id’,即1864.此外,std :: next不起作用,因为数据集可以具有匹配的id,不一定在下一个元素中.希望这有帮助!

请帮帮我!!!我的老板已经很失望,因为我花了这么多时间学习C(已经有3周了!)

解决方法

如果您有一个现代编译器(支持lambdas),您可以执行以下操作:
  1. const int prevToFind = 10;
  2. auto findResult = std::find_if(std::begin(table),std::end(table),[&](const std::pair<int,struct_t*> &pair)
  3. {
  4. return pair.second->prev == prevToFind;
  5. });
  6.  
  7. int foundKey = 0; // You might want to initialise this to a value you know is invalid in your map
  8. struct_t *foundValue = nullptr
  9. if (findResult != std::end(table))
  10. {
  11. foundKey = findResult->first;
  12. foundValue = findResult->second;
  13.  
  14. // Now do something with the key or value!
  15. }

如果您有一个较旧的编译器,请告诉我,我可以更新示例以使用谓词类.

猜你在找的C&C++相关文章