对于仅使用InputIterator or ForwardIterator 作为输入的算法,简单的强制转换就足够了。对于更复杂的算法writing a wrapper,可能需要编写专门的迭代器或使用 Boost 功能。只要算法输入与这些条件一致,这样的事情就会起作用:
ofstream foo("foo.txt", ios_base::binary);
vector<int> bar = {13, 42};
copy(reinterpret_cast<const char*>(&*bar.cbegin()), reinterpret_cast<const char*>(&*bar.cend()), ostreambuf_iterator(foo));
显然,这需要经过往返认证才能被认为是可靠的。验证 output 中的值是连续的可能很乏味,因此代码被劫持 from here 来做到这一点:
ofstream foo("foo.txt", ios::binary);
vector<int> bar(numeric_limits<unsigned char>::max() + 1);
iota(bar.begin(), bar.end(), 0);
copy(reinterpret_cast<const char*>(&*bar.data()), reinterpret_cast<const char*>(&*bar.data() + bar.size()), ostreambuf_iterator<char>(foo));
foo.close();
ifstream file_read("foo.txt", ios::binary);
vector<decltype(bar)::value_type> output(bar.size());
copy(istreambuf_iterator<char>(file_read), istreambuf_iterator<char>(), reinterpret_cast<char*>(&*output.data()));
cout << "First element: " << output.front() << "\nLast element: " << output.back() << "\nAny non-consecutive elements: " << (output.cend() == mismatch(output.cbegin(), prev(output.cend()), next(output.cbegin()), [](auto first1, auto first2) { return first1 + 1 == first2; }).second ? "no\n" : "yes\n");
output from this证明这个方法实际上是成功的:
第一个元素:0
最后一个元素:255
任何不连续的元素:没有
虽然不是所有可能的int 都被尝试过,但所有可能的char 都被尝试过,并且由于任何int 都可以由chars 的集合组成,这表明ints 的任何集合都是以这种方式流式传输。