I want to store a buffer data
. I will have to append data to data
in the form of BYTEs, WORDs, and DWORDs. What is the best way to implement data
? Is there something in the STL for this?
Asked
Active
Viewed 679 times
1

Brian Tompsett - 汤莱恩
- 5,753
- 72
- 57
- 129
-
2There must be *some* structure to the data you're storing. Can you give a few examples of the data? – Pete Wilson Sep 25 '11 at 17:21
-
1What other operations do you need on the buffer after it contains data? Do you need to remember the types of the contents or will it just be a chunk of raw bytes? – Blastfurnace Sep 25 '11 at 17:28
-
What are your criteria to define "best"? Do you favor size used by the storage, or complexity of the code, or speed? The solution will probably differs depending on your answer to that question. – Sylvain Defresne Sep 25 '11 at 17:48
-
You can try std::tuple, but some caveats: http://stackoverflow.com/questions/855110/why-is-the-use-of-tuples-in-c-not-more-common – chemelnucfin Sep 28 '11 at 16:32
2 Answers
0
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:
- Have a hierarchy of objects and store a reference/pointer to them (i.e.
std::vector< boost::shared_ptr<MyBaseObject> >
- 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.

Gilad Naor
- 20,752
- 14
- 46
- 53
0
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
}
}

Robᵩ
- 163,533
- 20
- 239
- 308