将 fstreams 数组传递给函数?

Passing an array of fstreams to a function?

我基本上是这样写的:-

void function(fstream& f[], int m){
// using fstream objects
}

int main()
{
    int m = 4;
    fstream f[m];
    f[0].open("f0.txt");
    f[1].open("f1.txt");
    f[2].open("f2.txt");
    f[3].open("f3.txt");

    function(f, m);

    return 0;
}

以下是即将出现的错误:-

error: declaration of ‘f’ as array of references|
error: expected ‘)’ before ‘,’ token|
error: expected unqualified-id before ‘int’|

所有这些错误都在第

void function(fstream& f[], int m){

如果我只是在函数内初始化 fstream 数组,错误就会消失。如果我在主函数中初始化它们,我应该怎么做才能消除它们?

主要问题是您试图将指针传递给引用,而不是数组。要解决此问题,您应该传递一个真正的指针 fstream * 或(更好)使用 ::std::array 代替:

using t_FileStreams = ::std::array<::std::fstream, 4>;

void sort(t_FileStreams & streams){
// using fstream objects
}

int main()
{
    t_FileStreams f;
    f[0].open("f0.txt");
    f[1].open("f1.txt");
    f[2].open("f2.txt");
    f[3].open("f3.txt");

    sort(f);

    return 0;
}

或者,如果事先不知道物品的数量,您可能想使用 std::vector<::std::fstream>。另请注意,代码 int m = 4; fstream f[m]; 在 C++ 中是不合法的,因为数组大小必须是编译时已知的常量。

考虑使用一些标准 container, probably std::vector or std::array

了解 rule of five

使用 std::sort. You can pass a lambda expression 给出比较标准。

你不能轻易地比较 std::fstream-s, because they don't keep their file path. Once you have given some path to an fstream (by open or at construction 时间),那条路迷路了。您需要自己明确保存它。

如果您想通过其他一些标准(例如它们的内容)比较文件,您最好在排序前 memoize that criteria (e.g. keep their content in some separate data). Any sorting functions would need to compare elements several times (since the sorting complexity is at least O(n log n)....), so doing IO in the compare function is unreasonable. Likewise, if you want to compare files by some metadata such as their size and/or creation time, better retrieve that metadata once (e.g. using stat(2) 上 Linux)。

也许您想定义自己的 classstruct 以将 std::stringsmart pointer (e.g. some std::unique_ptr) 保留给某些 std::fstream.

然后您将通过引用或 const 引用将此类对象的容器传递给您的函数。

在编码之前花几天阅读 good book on C++ programming

注意IO操作一般都是very slow。它们每个可能持续几毫秒(而大多数 CPU 操作只需要纳秒)。所以在传递给某些排序函数的比较代码中做IO通常是不合理的。

要将任意大小的数组传递给函数,您可以使用数组引用(声明为 Type(&Identifier)[Size])和这样的模板。

#include <cstddef>

template<std::size_t N>
void sort(std::ifstream(&ins)[N]) { /* implementation */ }

N是数组ins的大小,可以在sort的函数体内使用,就好像它是一个普通参数一样。

如果数组永远只有一个大小,您可以不使用模板。

void sort(std::ifstream(&ins)[4]) { /* implementation */ }

这也适用于 std::array

#include <array>
#include <cstddef>

template<std::size_t N>
void sort(std::array<std::ifstream, N> &ins) { /* implementation */ }