我有一个结构作为值类型的地图
- map<int id,struct_t*> table
- struct_t
- {
- int prev;
- int wt;
- string name;
- }
仅使用prev,我需要找到相应的id.非常感谢提前!
编辑:
- int key=0;
- for(auto it = table.begin(); it != table.end(); ++it)
- {
- if(table[(*it).first].prev == ?)
- }
这就是我的地图数据的样子:
- id prev abundance thing
- 1573 -1 0 book
- 1864 1573 39 beds
- 2075 1864 41 tray
- 1760 2075 46 cups
对于每个id,我需要找到NEXT匹配id.因此,对于来自prev列的1573,我需要找到匹配的’id’,即1864.此外,std :: next不起作用,因为数据集可以具有匹配的id,不一定在下一个元素中.希望这有帮助!
请帮帮我!!!我的老板已经很失望,因为我花了这么多时间学习C(已经有3周了!)
解决方法
如果您有一个现代编译器(支持lambdas),您可以执行以下操作:
- const int prevToFind = 10;
- auto findResult = std::find_if(std::begin(table),std::end(table),[&](const std::pair<int,struct_t*> &pair)
- {
- return pair.second->prev == prevToFind;
- });
- int foundKey = 0; // You might want to initialise this to a value you know is invalid in your map
- struct_t *foundValue = nullptr
- if (findResult != std::end(table))
- {
- foundKey = findResult->first;
- foundValue = findResult->second;
- // Now do something with the key or value!
- }
如果您有一个较旧的编译器,请告诉我,我可以更新示例以使用谓词类.