如何在迭代流缓冲区时摆脱无"matching function call error"?

How to get rid of no "matching function call error" when iterating over a stream buffer?

本文关键字:matching function call error 迭代 缓冲区      更新时间:2023-10-16

我正在尝试存储应该具有 std::complex<类型的二进制数据,通过迭代流缓冲区的每个元素>浮向量。但是我不断收到一个错误说

no matching function for call to ‘std::istreambuf_iterator<std::complex<float> >::istreambuf_iterator(std::ifstream&)’
 std::for_each(std::istreambuf_iterator<std::complex<float> >(i_f1),

我尝试寻找解决方案,但找不到任何可行的方法。我也在尝试遵循如何将整个流读取到 std::vector?.此外,我正在使用 g++ 和 -std=c++11 进行编译。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>
#include <boost/tuple/tuple.hpp>
#include <algorithm>
#include <iterator>
int main(){
    //path to files
    std::string data_path= "/$HOME/some_path/";
    //file to be opened
    std::string f_name1 = "ch1_d2.dat";

    std::ifstream i_f1(data_path + f_name1, std::ios::binary);
    if (!i_f1){
        std::cout << "Error occurred reading file "<<f_name1 <<std::endl;        std::cout << "Exiting" << std::endl;
        return 0;
     } 
    //Place buffer contents into vector 
    std::vector<std::complex<float> > data1;
    std::for_each(std::istreambuf_iterator<std::complex<float> >(i_f1), 
        std::istreambuf_iterator<std::complex<float> >(), 
        [&data1](std::complex<float> vd){
        data1.push_back(vd);
        });
   // Test to see if vector was read in correctly
   for (auto i = data1.begin(); i != data1.end(); i++){
        std::cout << *i << " ";
    }
    i_f1.close();
    return 0;
}

我对自己做错了什么感到非常迷茫,因此想知道为什么

std::istreambuf_iterator() 

不接受我将其作为参数的流?此外,错误消息让我感到困惑,因为它似乎暗示我以错误的方式调用该函数,或者调用不存在的函数。

谢谢

您想使用 operator>>i_f1(这是一个std::ifstream(中读取std::complex std::complex ,因此您需要一个std::istream_iterator而不是std::istreambuf_iterator 1

std::for_each(std::istream_iterator<std::complex<float> >(i_f1), 
    std::istream_iterator<std::complex<float> >(), 
    [&data1](std::complex<float> vd){
        data1.push_back(vd);
    });

您的代码实际上可以简化为:

std::vector<std::complex<float>> data1{
    std::istream_iterator<std::complex<float>>(i_f1), 
    std::istream_iterator<std::complex<float>>()};

1 std::istreambuf_iterator用于迭代每个字符,例如,一个std::basic_istream,而不是使用operator>>重载来迭代它。

您可能使用了错误的工具来完成这项工作。

您正在尝试使用缓冲区迭代器,该迭代器循环访问流缓冲区的组成部分。但是你告诉您的计算机缓冲区是complex<float>之一......它不是。ifstream的缓冲区为char s。因此,您尝试使用的构造函数(采用缓冲区为 complex<float>ifstream的构造函数(不存在。

您可以使用istream_iterator来执行格式化迭代,即使用流的神奇力量(在这种情况下,以词法方式将输入解释为 complex<float> s(,而不是直接访问其基础字节。

您可以在上一个问题"istreambuf_iteratoristream_iterator之间的区别">中阅读更多内容。

您链接到的示例也在某种程度上解释了这一点。

相关文章: