What is the best way to use two keys with a std::map?

后端 未结 9 1828
你的背包
你的背包 2021-01-30 03:54

I have a std::map that I\'m using to store values for x and y coordinates. My data is very sparse, so I don\'t want to use arrays or vectors, which would result in

9条回答
  •  长发绾君心
    2021-01-30 04:29

    First and foremost, ditch the string and use 2 ints, which you may well have done by now. Kudos for figuring out that a tree is the best way to implement a sparse matrix. Usually a magnet for bad implementations it seems.

    FYI, a triple compound key works too, and I assume a pair of pairs as well.

    It makes for some ugly sub-scripting though, so a little macro magic will make your life easier. I left this one general purpose, but type-casting the arguments in the macro is a good idea if you create macros for specific maps. The TresKey12 is tested and running fine. QuadKeys should also work.

    NOTE: As long as your key parts are basic data types you DON'T need to write anything more. AKA, no need to fret about comparison functions. The STL has you covered. Just code it up and let it rip.

    using namespace std;    // save some typing
    #define DosKeys(x,y)      std::make_pair(std::make_pair(x,y))
    #define TresKeys12(x,y,z) std::make_pair(x,std::make_pair(y,z))
    #define TresKeys21(x,y,z) std::make_pair(std::make_pair(x,y),z))
    
    #define QuadKeys(w,x,y,z) std::make_pair(std::make_pair(w,x),std::make_pair(y,z))
    
    
    map>, pIC_MESSAGE> MapMe;
    MapMe[TresKey12(Part1, Part2, Part3)] = new fooObject;
    

    If someone wants to impress me, show me how to make a compare operator for TresKeys that doesn't rely on nesting pairs so I can use a single struct with 3 members and use a comparison function.

    PS: TresKey12 gave me problems with a map declared as pair,z as it makes x,pair, and those two don't play nice. Not a problem for DosKeys, or QuadKeys. If it's a hot summer Friday though, you may find an unexpected side-effect of typing in DosEquis ... err.. DosKeys a bunch of times, is a thirst for Mexican beer. Caveat Emptor. As Sheldon Cooper says, "What's life without whimsy?".

提交回复
热议问题