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

后端 未结 9 1816
你的背包
你的背包 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:46

    Boost has a map container that uses one or more indices.

    Multi Index Map

    0 讨论(0)
  • 2021-01-30 04:48

    This will stuff multiple integer keys into a large integer, in this case, an _int64. It compares as an _int64, AKA long long (The ugliest type declaration ever. short short short short, would only be slightly less elegant. 10 years ago it was called vlong. Much better. So much for "progress"), so no comparison function is needed.

    #define ULNG  unsigned long
    #define BYTE  unsigned char
    #define LLNG  long long 
    #define ULLNG unsigned long long
    
    // --------------------------------------------------------------------------
    ULLNG PackGUID(ULNG SN,  ULNG PID, BYTE NodeId) {
        ULLNG CompKey=0;
    
        PID = (PID << 8) + NodeId;
        CompKey = ((ULLNG)CallSN << 32) + PID;
    
        return CompKey;
    }
    

    Having provided this answer, I doubt this is going to work for you, as you need two separate and distinct keys to navigate with in 2 dimensions, X and Y.

    On the other hand, if you already have the XY coordinate, and just want to associate a value with that key, then this works spectacularly, because an _int64 compare takes the same time as any other integer compare on Intel X86 chips - 1 clock.

    In this case, the compare is 3X as fast on this synthetic key, vs a triple compound key.

    If using this to create a sparsely populated spreadsheet, I would RX using 2 distinct trees, one nested inside the other. Make the Y dimension "the boss", and search Y space first to resolution before proceeding to the X dimension. Spreadsheets are taller than they are wide, and you always want the 1st dimension in any compound key to have the largest number of unique values.

    This arrangement would create a map for the Y dimension that would have a map for the X dimension as it's data. When you get to a leaf in the Y dimension, you start searching it's X dimension for the column in the spreadsheet.

    If you want to create a very powerful spreadsheet system, add a Z dimension in the same way, and use that for, as an example, organizational units. This is the basis for a very powerful budgeting/forecasting/accounting system, one which allows admin units to have lots of gory detail accounts to track admin expenses and such, and not have those accounts take up space for line units which have their own kinds of detail to track.

    0 讨论(0)
  • 2021-01-30 04:48

    Use std::pair. Better even use QHash<QPair<int,int>,int> if you have many of such mappings.

    0 讨论(0)
提交回复
热议问题