c++ - 流迭代器 - 字节流

标签 c++ c++11

使用 istream_iterator 可以轻松地将文件读入字节数组。

例如:

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

我现在需要能够对 vector 和字符串执行相同的操作。问题是这些尺寸会很大。

例如:

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>*/};

我一直在查看 cpp 引用资料,但没有找到一种方法可以将上述内容视为字节流,而无需滚动我自己的流。 有没有人有任何建议或引用可以指向我?我将不胜感激。

最佳答案

您可以使用完全相同的迭代器构造函数

#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';
}

关于c++ - 流迭代器 - 字节流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32195364/

相关文章:

C++ 标记强制保留参数为 nullptr

c++ - 构造函数采用 shared_ptr

c++ - 如何在 Mac 终端中使用 C++11 支持编译 C++

c++ - 如何检测 Linux/MacOs 平台中的内存泄漏?

c++ - 如何从 gprof 中排除某个函数?

c++ - 大括号中的类名后面是什么? C++

c++ - 使用 std::bind 的功能组合

c++ - 像 std::vector 中的元素一样就地合并

c++ - 避免条件代码编译

c++ - 错误: reference to overloaded function could not be resolved