Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is it possible to store a structure in a map?
and, if yes, how?
e.g.:
C++
struct struct1
{
int a;
int b;
float c;
fload d;
};


key of the map should be c and the mapped value should contain entire structure.
Posted
Updated 17-Oct-12 2:03am
v2
Comments
CPallini 17-Oct-12 8:02am    
skydger gave you the solution. I would add that using float values as map keys is (unless you really know what are you doing) not a good idea. See
http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

1 solution

Yes, it is possible, try this code
C++
typedef struct struct1{
    int a;
    int b;
    float c;
    float d;
} my_struct_t;
//...
my_struct_t st = { 1, 2, 3.0, 4,0 };
std::map< float, my_struct_t > my_struct_map;
std::pair< float, my_struct_t > p = std::make_pair( st.c, st );
my_struct_map.insert(p);
 
Share this answer
 
v2
Comments
CPallini 17-Oct-12 7:58am    
My 5.
Note you don't need the typedef.
skydger 17-Oct-12 8:14am    
Thanks for advice :)
CPallini 17-Oct-12 8:30am    
You are welcome.
newbie@work 17-Oct-12 8:44am    
Thank you guys. I was doing the same thing, one crazy error was that I was declaring the structure in the same locale scope. Because of which I couldnt store the object in the map. Stupid, Stupid me!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900