I have a map with the pointer of a struct as key.
std::map < struct1*, struct2>;
struct struct1{ int x; char a[10]; }; struct struct2 { int x; };
The key is the pointer to struct1. the struct1 has the member called x.
I have to search the map by the member x of struct1.
Is it possible to search without looping through all the elements in the map?
I tried below code but it is not working.
include <iostream>
#include <map>
struct struct1 { int x; char a[10]; };
struct struct2{ int x; };
bool operator<(const struct1 & fk1, const struct1& fk2) {
return fk1.x < fk2.x;
}
int main()
{
std::map<struct1 *, struct2> m;
struct1 *f1 = new struct1();
f1->x =1;
strcpy(f1->a,"ab");
struct2 l1;
l1.x=10;
m.insert(std::make_pair(f1, l1));
struct1 fk1;
fk1.x=1;
std::map<struct1 *, struct2>::iterator x = m.find(&fk1);
if(x != m.end())
{
std::cout << x->first->x <<std::endl;
std::cout << x->first->a <<std::endl;
}
if(f1!=NULL)
delete f1;
return 0;
}