如何使用地图C++中的值获取匹配键

sna*_*iii 8 c++ struct stl map

我有一个结构作为值类型的地图

map<int id, struct_t*> table

struct_t
{
int prev;
int wt;
string name;
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

int key=0;
for(auto it = table.begin(); it != table.end(); ++it)
{
     if(table[(*it).first].prev == ?)
}
Run Code Online (Sandbox Code Playgroud)

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

id    prev abundance  thing
1573  -1      0       book
1864  1573    39      beds
2075  1864    41      tray
1760  2075    46      cups
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*ram 7

如果您有一个现代编译器(支持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!
}
Run Code Online (Sandbox Code Playgroud)

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


fas*_*ked 5

简单的循环就可以做到:

#include <map>
#include <string>
#include <iostream>

int main()
{
   std::map<int, std::string> m = {
      std::make_pair(0, "zero"), std::make_pair(1, "one"), std::make_pair(2, "two")
   };

   int key = 0;
   for (auto &i : m) {
      if (i.second == "two") {
         key = i.first;
         break; // to stop searching
      }
   }

   std::cout << key << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

当然,您需要设置自己的if语句进行搜索。请注意,boost双向地图可能是一个解决方案(boost :: bimap


Hen*_*rik 5

遍历地图当然可以解决问题,但是您可能需要考虑使用第二个地图作为索引:

map<int,int> table_idx;
Run Code Online (Sandbox Code Playgroud)

每当您向其中添加新条目时,table您都需要进行更新table_idx,并存储id与every对应的prevtable_idx然后将允许您反向查询idlog(N)时间:

int prev_for_id = table_idx[id];
Run Code Online (Sandbox Code Playgroud)