本文是小编为大家收集整理的关于从一个std::vector<bool>中获取字节数的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。
问题描述
我有类似以下内容,在用任意数量的位填充它之后,我需要将字节写入文件.我看不到这样做的方法,这似乎有用,所以我必须缺少一些东西.有什么想法吗?
std::vector<bool> a; a.push_back(true); a.push_back(false); a.push_back(false); a.push_back(true); a.push_back(false); a.push_back(true); a.push_back(true); a.push_back(false);
推荐答案
std::vector <bool>实际上不包含布尔(即bytes),它包含位!这主要是一个杂物,建议您使用std::deque <bool>,而没有此"功能".
,如果您希望存储是连续的,请使用std::vector <char>.
其他推荐答案
尝试此
void WriteOut(fstream& stream, const vector<bool>& data) { for (vector<bool>::const_iterator it = data.begin(); it != data.end(); it++) { stream << *it; } }
其他推荐答案
布尔通常是一个字节 - 您可以使用向量:: iterator在向量上迭代,然后以这种方式访问每个值.
std::vector<bool> a; a.push_back(true); a.push_back(false); for(std::vector<bool>::iterator iter = a.begin(); iter != a.end(); ++iter) { std::cout << *iter << std::endl; }
将在每个布尔上迭代,然后将其打印到命令行.打印到文件相对简单.
问题描述
I have something like the following, and after populating it with a arbitrary number of bits, I need to get the bytes to write out to a file. I don't see a way to do this and it seems useful, so I must be missing something. Any idea's?
std::vector<bool> a; a.push_back(true); a.push_back(false); a.push_back(false); a.push_back(true); a.push_back(false); a.push_back(true); a.push_back(true); a.push_back(false);
推荐答案
std::vector <bool> does not actually contain bools (i.e.bytes) , it contains bits! This is mostly a missfeature and you are advised to use std::deque <bool>, which doesn't have this "feature" instead.
And if you want the storage to be contiguous, use std::vector <char>.
其他推荐答案
Try this
void WriteOut(fstream& stream, const vector<bool>& data) { for (vector<bool>::const_iterator it = data.begin(); it != data.end(); it++) { stream << *it; } }
其他推荐答案
A bool is normally a byte - you can simply iterate over the vector using the vector::iterator, and access each value that way.
std::vector<bool> a; a.push_back(true); a.push_back(false); for(std::vector<bool>::iterator iter = a.begin(); iter != a.end(); ++iter) { std::cout << *iter << std::endl; }
Will iterate over each bool, and print it out to the command line. Printing to a file is relatively straightforward.