2

我想使用以下代码段

#include <iostream>
#include <iterator>
#include <vector>
#include <bitset>
#include <algorithm> 

int _tmain(int argc, _TCHAR* argv[])
{   
    static const char szBits[] = "110101011010";   
    std::vector<std::bitset<4> > str(szBits, szBits + sizeof szBits);   
    std::copy(str.begin(), str.end(), std::ostream_iterator<std::bitset<4> > (std::cout, "\n")); 

    return 0;
}

得到一个包含 3 个元素的向量看起来像 1101 1010 1010

但我无法获得预期的正确结果。

你可以帮帮我吗?谢谢!

4

1 回答 1

2
std::vector<std::bitset<4> > str(szBits, szBits + sizeof szBits);

这显然是错误的。它实际上是从每个创建向量的项目char,而不是4 char一起创建。

这是你应该做的:

static const char szBits[] = "110101011010";   
std::vector<std::bitset<4> > str;
for(size_t i = 0 ; (i + 4) < sizeof(szBits) ; i += 4 )
      str.push_back(std::bitset<4>(std::string(&szBits[i], 4))); 

std::copy(str.begin(), str.end(), std::ostream_iterator<std::bitset<4> > (std::cout, "\n")); 

输出:

1101
0101
1010

演示:http ://www.ideone.com/27RNL

于 2011-05-26T06:32:15.163 回答