我要使用下面的代码段
#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 个元素的 vector 看起来像 1101 1010 1010
但我无法获得我所期望的正确结果。
你能帮帮我吗?谢谢!
最佳答案
std::vector<std::bitset<4> > str(szBits, szBits + sizeof szBits);
这显然是错误的。它实际上是从每个 char
而非 4 个 char
一起创建 vector 的项目。
这是你应该做的:
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
关于c++ - 将 char 数组转换为具有 4 位元素的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6134440/