How to get the corresponding key using a value on a C ++ map

I have a map with a structure as a value type

map<int id, struct_t*> table struct_t { int prev; int wt; string name; } 

Using only prev, I need to find the corresponding id. Thanks for that in advance!

EDIT:

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

Here's what 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 

For each identifier, I need to find the NEXT-matching identifier. So, for 1573 from the previous column, I need to find the corresponding "id", which is 1864. In addition, std :: next does not work, because the data set may not have the corresponding identifiers in the next element. Hope this helps

PLEASE PLEASE help me !!! My boss is already disappointed that I have so much time to learn C ++ (it has been 3 weeks already!)

+6
source share
4 answers

If you have 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 this example to use the predicate class.

+5
source

A simple loop can do this:

 #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; } 

Of course, you need to configure your own if-statement for the search. Note that raising a bidirectional map may be a solution ( boost :: bimap )

+3
source

Quoting on a map, of course, does the trick, but you might want to use the second map as an index:

 map<int,int> table_idx; 

Whenever you add new records to table , you also need to update table_idx , keeping the id that matches each prev . table_idx will then allow you to do a reverse id lookup in the log (N):

 int prev_for_id = table_idx[id]; 
+3
source

I get the feeling that you are a beginner, so it would be nice if you told us what you were trying to do, because maybe you are trying to solve the wrong problem.
As marked cards are designed to search by keyword, not by value.
If you insist on looking for a map this way, you probably want to check out the Boost Bimap .

+1
source

Source: https://habr.com/ru/post/927011/


All Articles