繁体   English   中英

从istreambuf_iterator构造时无法获得向量大小

[英]Cannot get vector size when constructed from istreambuf_iterator

我正在尝试读取一个充满std::complex<float>的二进制文件。 我尝试了以下代码, 如该SO答案所示

#include <complex>
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <vector>


void readRawFile(const std::string inputFile){
    std::ifstream input(inputFile, std::ios::binary);
    std::vector<std::complex<float>> auxBuffer(std::istreambuf_iterator<std::complex<float>>(input), std::istreambuf_iterator<std::complex<float>>());
    std::cout << "Number of raw samples read: " << auxBuffer.size();
}

int main(){
    readRawFile("myRawFile.raw");
    return 0;
}

我得到以下编译错误:

In function 'void readRawFile(std::string)': 12:59: error: request for member 'size' in 'auxBuffer', which is of non-class type 'std::vector<std::complex<float> >(std::istreambuf_iterator<std::complex<float> >, std::istreambuf_iterator<std::complex<float> > (*)())'

我不明白为什么我不能访问刚创建的向量的size方法而没有编译错误。 我想它与向量的创建方式有关,但是对我来说奇怪的是它在那里没有给出错误。

有什么解释吗?

您复制的答案显示了如何将流中的原始字符读入缓冲区。 这是istreambuf_iterator的正确用法。

您正在尝试从流中提取复数。 这是完全不同的操作,涉及读取字符,然后使用operator<<解析它们 那不是istreambuf_iterator目的。 istreambuf_iterator<complex<float>>将尝试从basic_streambuf<complex<float>>中提取类型为complex<float>字符,这是毫无意义的。 这不是字符类型,并且不能有包含复数作为其原始字符的流缓冲。

istreambuf_iterator用于从streambuf中读取单个字符,而不是解析字符并将其解释为(复数)数字或其他类型。

您需要使用std::istream_iterator<X>从istream中提取X值,因此,在修复最令人讨厌的解析之后,您需要使用std::istream_iterator<std::complex<float>>作为迭代器类型。

您已经达到了C ++的Most Vexing Parse的要求 您的声明被解释为函数声明:

您可以:

void readRawFile(const std::string inputFile){
    std::ifstream input(inputFile, std::ios::binary);

    auto start = std::istream_iterator<std::complex<float>>(input);
    auto stop = std::istream_iterator<std::complex<float>>();

    std::vector<std::complex<float>> auxBuffer(start, stop);
    std::cout << "Number of raw samples read: " << auxBuffer.size();
}

或使用统一括号初始化(C ++ 11):

void readRawFile(const std::string inputFile){
    std::ifstream input(inputFile, std::ios::binary);
    std::vector<std::complex<float>> auxBuffer{std::istream_iterator<std::complex<float>>(input), std::istream_iterator<std::complex<float>>()};
    std::cout << "Number of raw samples read: " << auxBuffer.size();
}

这里

暂无
暂无

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

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