简体   繁体   English

流迭代器-字节流

[英]Stream Iterators - stream of bytes

Reading files into an array of bytes can easily be accomplished using istream_iterator. 使用istream_iterator可以轻松地将文件读取为字节数组。

For example: 例如:

std::ifstream afile(somefile);
noskipws(afile);
...
std::vector<uint_8> vOfBytes = { std::istream_iterator<uint8_t>(afile),
                                 std::istream_iterator<uint8_t>() };

I now have a need to be able to do the same with vectors and strings. 现在,我需要能够对向量和字符串执行相同的操作。 The problem is that these will very in size. 问题是这些将非常庞大。

For example: 例如:

std::string astring = "abc";
std::wstring awstring = L"abc";
std::vector avector<uint32_t> = { 0, 1, 2, 3 };

// std::distance(asv.begin(), asv.end()) == 3
std::vector<uint8_t> asv = { /* astring to std::vector<uint8_t> */ }; 

// std::distance(awsv.begin(), awsv.end()) == 6
std::vector<uint8_t> awsv = { /* awstring to std::vector<uint8_t> */ };

// std::distance(uiv.begin(),uiv.end()) == 16
std::vector<uint8_t> uiv = { /* avectorto std::vector<uint8_t>*/};

I have been looking through the cpp reference for a bit and have not come across a way to treat the above as a stream of bytes w/o having to roll my own stream. 我一直在寻找cpp参考,并没有遇到一种将上述内容视为字节流而不必滚动自己的流的方法。 Does anyone have any suggestions or references they could point me towards? 有人对我有什么建议或参考吗? I would greatly appreciate it. 我将不胜感激。

You can use the very same iterator constructor 您可以使用完全相同的迭代器构造函数

#include <string>
#include <vector>
#include <iostream>

int main()
{
  std::string astring = "abc";
  std::wstring awstring = L"abc";
  std::vector<uint32_t> avector{ 0, 1, 2, 3 };

  std::vector<uint8_t> asv{
    reinterpret_cast<uint8_t const*>(astring.data()),
    reinterpret_cast<uint8_t const*>(astring.data() + astring.size()),
  }; 

  std::vector<uint8_t> awsv{
    reinterpret_cast<uint8_t const*>(awstring.data()),
    reinterpret_cast<uint8_t const*>(awstring.data() + awstring.size()),
  }; 

  std::vector<uint8_t> uiv{
    reinterpret_cast<uint8_t const*>(avector.data()),
    reinterpret_cast<uint8_t const*>(avector.data() + avector.size()),
  };

  std::cout << std::hex;

  for (auto v : asv)
    std::cout << static_cast<int>(v) << ' ';
  std::cout << '\n';
  for (auto v : awsv)
    std::cout << static_cast<int>(v) << ' ';
  std::cout << '\n';
  for (auto v : uiv)
    std::cout << static_cast<int>(v) << ' ';
  std::cout << '\n';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM