在std :: bitset和std :: vector< bool>之间转换 [英] Converting Between std::bitset and std::vector<bool>

查看:96
本文介绍了在std :: bitset和std :: vector< bool>之间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std::bitset,但是现在我想在其上使用STL算法.

I have a std::bitset but now I want to use an STL algorithm on it.

本来可以使用std::vector<bool>,但是我喜欢std::bitset的构造函数,并且我希望std::bitset的按位运算.

I could have used std::vector<bool> instead, but I like std::bitset's constructor and I want std::bitset's bitwise operations.

我是否必须经过循环并将所有内容填充到std::vector<bool>中才能使用STL算法,然后将其复制回std::bitset,还是有更好的方法?

Do I have to go through a loop and stuff everything in a std::vector<bool> to use STL algorithms, and then copy that back to the std::bitset, or is there a better way?

推荐答案

Matthew Austern在此处为bitset写了一个迭代器:

Matthew Austern wrote an iterator for bitset here: http://www.drdobbs.com/the-standard-librarian-bitsets-and-bit-v/184401382?pgno=2

它超过100行,所以我觉得只是将其抬起并放入答案中可能有点超出范围.但是它对于STL算法非常有用.

It's over 100 lines so I feel just lifting it and putting it in this answer may be a bit out of bounds. But it works marvelously for STL algorithms.

澳大利亚人回答了这个确切的问题:

Austern answers this exact question:

虽然位集没有STL容器接口,但它仍然是一个非常好的(固定大小)容器.如果使用位集对您有意义,并且还需要迭代器,则可以定义一个简单的索引迭代器"适配器,将* i等迭代器符号转换为b [n]等数组符号.该实现非常简单:维护一个索引和一个指向容器的指针.

While bitset doesn’t have the STL container interface, it’s still a perfectly good (fixed-size) container. If it makes sense for you to use a bitset, and if you also need iterators, then you can define a simple "index iterator" adaptor that translates iterator notation like *i into array notation like b[n]. The implementation is straightforward: maintain an index and a pointer to a container.

他确实警告了迭代器:

如果我们愿意接受稍微麻烦一些的接口,则可以定义一个类,该类适用于任意类似数组的类型.通用索引迭代器适配器在处理STL之前的容器类时有时甚至在处理诸如vector之类的STL容器时通常很有用.

If we were willing to accept a slightly more cumbersome interface, we could define a class that worked with arbitrary array-like types. A general purpose index iterator adaptor is often useful when dealing with pre-STL container classes, and sometimes even when dealing with STL containers like vector.

还应注意,与vector<bool>::iterator一样,Austern的bitset_iterator::operator*不会返回bool&,而是返回代理引用:bitset<>::reference.

It should also be noted that just as with a vector<bool>::iterator, Austern's bitset_iterator::operator* doesn't return a bool& but a proxy reference: bitset<>::reference.

bitset_iterator的用法如下:

std::bitset<10> foo;
std::vector<bool> bar(begin(foo), end(foo));

这篇关于在std :: bitset和std :: vector&lt; bool&gt;之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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