本文介绍了在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写了一个迭代器: http://www.drdobbs.com/the-standard-librarian-bitsets-and-bit-v/184401382?pgno=2

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:

他确实警告了迭代器:

还应注意,与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;之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:48