如何使用地图C ++中的值获取匹配键 [英] how to get matching key using the value in a map C++
问题描述
我有一个带有struct作为值类型的映射
I have a map with a struct as a value type
map<int id, struct_t*> table
struct_t
{
int prev;
int wt;
string name;
}
仅使用上一个,我需要找到相应的ID.提前非常感谢!
Using only prev, I need to find the corresponding id. Thanks so much in advance!
int key=0;
for(auto it = table.begin(); it != table.end(); ++it)
{
if(table[(*it).first].prev == ?)
}
这是我的地图数据的样子:
This is how my map data looks like:
id prev abundance thing
1573 -1 0 book
1864 1573 39 beds
2075 1864 41 tray
1760 2075 46 cups
对于每个ID,我需要找到下一个匹配ID.因此,对于prev列中的1573,我需要找到一个匹配的'id',即1864.而且,std :: next不起作用,因为数据集不一定在下一个元素中具有匹配的ID.希望这会有所帮助!
For each id, I need to find the NEXT matching id. So, for 1573 from the prev column I need to find a matching 'id' which is 1864. Also, std::next doesn't work because the data set can have the matching ids not necessarily in the next element.Hope this helps!
请帮助我!!!我的老板已经很失望,因为我花了太多时间学习C ++(已经3个星期了!)
PLEASE PLEASE help me!!! MY boss is already disappointed that I'm taking so much time to learn C++ (its been 3 weeks already!)
推荐答案
如果您拥有现代的编译器(支持lambda),则可以执行以下操作:
If you've got a modern compiler (supports lambdas), you can do the following:
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!
}
如果您使用的是较旧的编译器,请告诉我,我可以将示例更新为使用谓词类.
Let me know if you have an older compiler, and I can update the example to use a predicate class instead.
这篇关于如何使用地图C ++中的值获取匹配键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!