“适当的”方式使用C ++ / STL存储二进制数据 [英] "Proper" way to store binary data with C++/STL

查看:268
本文介绍了“适当的”方式使用C ++ / STL存储二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,在C ++中存储二进制数据的最好方法是什么?根据我可以告诉的选项,几乎可以归结为使用字符串或向量< char> s。 (我将省略char * s和malloc()的可能性,因为我特指C ++)。

In general, what is the best way of storing binary data in C++? The options, as far as I can tell, pretty much boil down to using strings or vector<char>s. (I'll omit the possibility of char*s and malloc()s since I'm referring specifically to C++).

通常我只使用一个字符串,我不确定是否有开销我缺少,或者STL内部的转换,可能会弄乱二进制数据的健全。有没有人有任何指针(har)在这?

Usually I just use a string, however I'm not sure if there are overheads I'm missing, or conversions that STL does internally that could mess with the sanity of binary data. Does anyone have any pointers (har) on this? Suggestions or preferences one way or another?

推荐答案

向量的char是很好的,因为内存是连续的。因此,您可以使用它与许多C API的berkley套接字或文件API。您可以执行以下操作,例如:

vector of char is nice because the memory is contiguious. Therefore you can use it with a lot of C API's such as berkley sockets or file APIs. You can do the following, for example:

  std::vector<char> vect;
  ...
  send(sock, &vect[0], vect.size());

并且可以正常工作。

你基本上可以像任何其他动态分配的char缓冲区一样对待它。你可以上下扫描寻找魔法数字或模式。您可以部分解析它到位。对于从套接字接收,你可以很容易地调整它的大小,以附加更多的数据。

You can essentially treat it just like any other dynamically allocated char buffer. You can scan up and down looking for magic numbers or patters. You can parse it partially in place. For receiving from a socket you can very easily resize it to append more data.

缺点是调整大小是不是非常有效(调整大小或preallocate谨慎)的数组也将非常缺乏。如果你需要,例如,一次只弹出一个或两个字符离开数据结构的前面很频繁,在这个处理之前复制到一个deque可能是一个选项。这会花费你一个副本和deque内存不是连续的,所以你不能只传递一个指针到C API。

The downside is resizing is not terribly efficient (resize or preallocate prudently) and deletion from the front of the array will also be very ineficient. If you need to, say, pop just one or two chars at a time off the front of the data structure very frequently, copying to a deque before this processing may be an option. This costs you a copy and deque memory isn't contiguous, so you can't just pass a pointer to a C API.

底线,在潜水之前了解数据结构及其权衡,然而char的向量通常是我在一般实践中使用的。

Bottom line, learn about the data structures and their tradeoffs before diving in, however vector of char is typically what I see used in general practice.

这篇关于“适当的”方式使用C ++ / STL存储二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆