如何迭代到一个较小的容器(即步幅!= 1)

Tom*_*Tom 3 c++ iterator stl stl-algorithm

还有一个问题,就是在精神上非常相似这里.不幸的是,这个问题没有引起太多反应 - 我想我会问一个更具体的问题,希望可以提出另一种方法.

我正在写一个二进制文件到std::cin(with tar --to-command=./myprog).二进制文件碰巧是一组浮点数,我想把数据放入std::vector<float>- 理想情况下是c ++方式.

我可以std::vector<char>很好地生成(感谢 这个答案)

#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>

int
main  (int ac, char **av)
{
  std::istream& input = std::cin;
  std::vector<char> buffer;
  std::copy( 
        std::istreambuf_iterator<char>(input), 
           std::istreambuf_iterator<char>( ),
           std::back_inserter(buffer)); // copies all data into buffer
}
Run Code Online (Sandbox Code Playgroud)

我现在想把我std::vector<char>变成一个std::vector<float>,大概是std::transform和一个执行转换的函数(a char[2]到a float,比方说).然而,我正在努力,因为我std::vector<float>将拥有一半的元素std::vector<char>.如果我可以以2的步幅进行迭代,那么我认为我会没事的,但从上一个问题来看,似乎我不能这样做(至少不是优雅的).

Mar*_*ork 5

我会编写自己的类来读取两个字符并将其转换为浮点数.

struct FloatConverter
{
    // When the FloatConverter object is assigned to a float value
    // i.e. When put into the vector<float> this method will be called
    //      to convert the object into a float.
    operator float() { return 1.0; /* How you convert the 2 chars */ }

    friend std::istream& operator>>(std::istream& st, FloatConverter& fc)
    {
        // You were not exactly clear on what should be read in.
        // So I went pedantic and made sure we just read 2 characters.
        fc.data[0] = str.get();
        fc.data[1] = str.get();
        retun str;
    }
    char   data[2];
 };
Run Code Online (Sandbox Code Playgroud)

根据GMan的评论:

struct FloatConverterFromBinary
{
    // When the FloatConverterFromBinary object is assigned to a float value
    // i.e. When put into the vector<float> this method will be called
    //      to convert the object into a float.
    operator float() { return data }

    friend std::istream& operator>>(std::istream& st, FloatConverterFromBinary& fc)
    {
        // Use reinterpret_cast to emphasis how dangerous and unportable this is.
        str.read(reinterpret_cast<char*>(&fc.data), sizeof(float));
        retun str;
    }

    float  data;
};
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

int main  (int ac, char **av)
{
  std::istream& input = std::cin;
  std::vector<float> buffer;

  // Note: Because the FloatConverter does not drop whitespace while reading
  //       You can potentially use std::istream_iterator<>
  //
  std::copy( 
           std::istreambuf_iterator<FloatConverter>(input), 
           std::istreambuf_iterator<FloatConverter>( ),
           std::back_inserter(buffer));
}
Run Code Online (Sandbox Code Playgroud)