C++ vector with dynamic item size

前端 未结 9 2239
无人及你
无人及你 2021-01-14 16:54

the C++ STL vector has a lot of decent properties, but only works when the size of each item is known at run-time.

I would like to have a vector class that features

9条回答
  •  星月不相逢
    2021-01-14 17:27

    If its just a sequence of int and double, then you can simply use:

     std::vector sequence;
    

    and then insert int and double into it. However, this approach doesn't keep track of the type of the items. If the type is critical for you, then probably the following may help you:

    struct item
    {
      union 
      {
         int i;
         double d;
      } data;
      char type; //store 0 for int, 1 for double;
    };
    
    std::vector sequence;
    

    Of course, this approach costs you atleast one extra byte per item, for storing the type of the item. You may want to use #pragma pack techniques to squeeze the extra padding.

    Or even better would redesigning your code such that you've two sequences instead of one:

    std::vector     intSeq;
    std::vector  doubleSeq;
    

提交回复
热议问题