开发者

Best way to store large amounts of different types of data?

开发者 https://www.devze.com 2023-04-08 20:08 出处:网络
I want to store a buffer data. I will have to append data to data in the form of BYTEs, WORDs, and DWORDs. What 开发者_C百科is the best way to implement data? Is there something in the STL for this?Fr

I want to store a buffer data. I will have to append data to data in the form of BYTEs, WORDs, and DWORDs. What 开发者_C百科is the best way to implement data? Is there something in the STL for this?


From the little you've said, it sounds like you want to have different types in an STL container. There are two ways to do this:

  1. Have a hierarchy of objects and store a reference/pointer to them (i.e. std::vector< boost::shared_ptr<MyBaseObject> >
  2. Use boost::variant (i.e. std::vector< boost::variant<BYTE, WORD, DWORD> >)

If, however, you need to interface with some legacy C code, or send raw data over the network, this might not be the best solution.


If you want to create a contiguous buffer of completely unstructured data, consider using std::vector<char>:

// Add an item to the end of the buffer, ignoring endian issues
template<class T>
addToVector(std::vector<char>& v, T t)
{
  v.insert(v.end(), reinterpret_cast<char*>(&t), reinterpret_cast<char*>(&t+1));
}

// Add an item to end of the buffer, with consistent endianness
template<class T>
addToVectorEndian(std::vector<char>&v, T t)
{
  for(int i = 0; i < sizeof(T); ++i) {
    v.push_back(t);
    t >>= 8; // Or, better: CHAR_BIT
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号