How can I use an array as map value?

后端 未结 8 1497
太阳男子
太阳男子 2020-12-01 08:04

I\'m trying to create a map, where the key is an int, and the value is an array as follows:

int red[3]   = {1,0,0};
int green[3] = {0,1,0};
int b         


        
8条回答
  •  猫巷女王i
    2020-12-01 08:40

    Approach using structure in C++

    int MAX_DATA_PER_INSTR = 8;
    //struct to hold the values. remember to write the constructor
    struct InstrChar
    {
      InstrChar(int in[MAX_DATA_PER_INSTR]) { 
        //c alternative is memcopy
        std::copy(in, in+MAX_DATA_PER_INSTR, data);
      }
      int data[MAX_DATA_PER_INSTR];
    };
    
    // create a key value pair 
    std::map  address_instructions;
    std::map ::iterator it;
    
    // sample array, 8 elements
    int xp[MAX_DATA_PER_INSTR ] = {31,4,3,4,4,3,1,2};
    address_instructions.insert(std::pair(PC, xp));
    it = address_instructions.find(PC);
    InstrChar buf1 = it->second;
    //integer pointer to the array, can be dereferenced as *p, *(p+1), ....    //*(p+7)
    int *p = buf1.data;
    
    //in case you need to print these values out. They can also be referred to as buf1.data[0], buf1.data[1], buf1.data[2]
    printf("%d\n", (*p));
    printf("%d\n", *(p+1));
    printf("%d\n", *(p+2));
    printf("%d\n", *(p+3));
    printf("%d\n", *(p+4));
    printf("%d\n", *(p+5));
    printf("%d\n", *(p+6));
    printf("%d\n", *(p+7));
    

提交回复
热议问题