从字符串设置 boostdynamic_bitset
我有一个需要的用例 您能否
boost::dynamic_bitset<unsigned char> , from a std::string buffer.
建议如何进行此操作。 所以我需要想出一个函数
void populateBitSet (std::string &buffer,
boost::dynamic_bitset<unsigned char> & bitMap) {
//populate bitMap from a string buffer
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您有这样的二进制数据:
您想像这样初始化它(结果有一个 处理这种情况的构造函数):
如果您想要原始数据,请使用 迭代器构造函数:
这些最终会分配所需的内存两次,因此您最好使用堆栈分配和交换。 或者您可以等到 C++0x,让移动语义完成它们的工作。
编辑:
为了澄清为什么第一个版本分配两倍的内存:
看一下编写第一个版本的另一种方式:
如果将这两行放在一起,如第一个示例所示,您仍然会在堆栈上得到一个临时构造,然后是一项任务。 1. boost需要为整组位分配足够的内存。 在2中,boost需要再次分配足够的内存来保存同一组位,然后复制这些值。 bitMap 可能已经拥有足够的内存,因此它可能并不总是需要重新分配,但也有可能它会释放其后备内存并从头开始重新分配。
大多数适合 stl 模具的容器还具有交换功能,当您打算丢弃交换的一侧时,可以使用该功能来代替分配。 这些通常是 O(1) 并且不会抛出异常,因为它们通常只涉及交换一些指针。 请参阅此 GotW 了解这些有用的另一个原因。
在 C++0X 中,您将能够使用赋值,并且仍然可以获得交换的优势。 由于您可以重载 r 值(如临时值),因此容器知道当您分配临时值时,它知道它可以蚕食临时值并基本上进行交换。 Visual Studio 团队博客介绍了右值和移动语义 这里很好。
If you have binary data like this:
You want to initialize it like this (turns out there's a constructor that handles this case):
If you want the raw data, use the iterator constructor:
These do end up allocating the needed memory twice, so you might be better off with a stack allocation and a swap. Or you just can wait until C++0x and let the move semantics do their thing.
Edit:
To clarify why the first versions allocate twice as much memory:
Take a look at another way to write the first version:
If you put these two lines together, as in the first example, you still get a temporary constructed on the stack, followed by an assignment. In 1. boost needs to allocate enough memory for the entire set of bits. In 2, boost needs to allocate again enough memory to hold that same set of bit and then copy the values over. It's possible that bitMap already has enough memory, so it may not always need to reallocate, but it's also possible that it will free its backing memory and reallocate from scratch anyway.
Most containers that fit the stl mold also have a swap function that you can use in place of assignment when you intend to throw away one side of the swap. These are usually O(1) and non-throwing as they often just involve swapping some pointers. See this GotW for another reason why these are useful.
In C++0X, you'll be able to use assignment, and still get the advantages of swap. Since you can overload on r-values (like the temporary), the container know that when you assign a temporary, it knows that it can cannibalize the temp and basically do a swap. The Visual Studio Team Blog has covered rvalues and move semantics quite well here.