0

我正在做一个编程问题,并正在使用 freopen 重定向流。我面临的问题是在 stdout 重定向之后printf命令没有在输出文件上打印。我什至尝试使用 fflush 但没有得到任何结果。

这是我的代码

    #include<iostream>
    #include<vector>
    #include<cmath>
    #define fc(a) static_cast<float>(a)
    using namespace std;
    
    vector<int>* touch(const vector<int> arr[], int size)
    {
        vector<int>* touch_circles = (vector<int>*)malloc(sizeof(vector<int>)*size);
        int i1, i2, dis;
        for(i1 = 0; i1 < size; i1++)
        for(i2 = i1+ 1; i2 < size; i2++)
        {
            dis = static_cast<int>(ceil(pow(pow(fc(arr[i1][0]) - fc(arr[i2][0]),2) + pow(fc(arr[i1][1]) - fc(arr[i2][1]),2),0.5)));
            if (dis <= arr[i1][2] + arr[i2][2])
            {
                touch_circles[i1].push_back(i2);
                touch_circles[i2].push_back(i1);
            }
        }
        return touch_circles;
    }
    
    int main()
    {
        #ifndef ONLINE_JUDGE
        freopen("D:\\C++\\input.txt","r",stdin);
        freopen("D:\\C++\\output.txt","w",stdout);
        freopen("D:\\C++\\output.txt","w",stderr);
        #endif
        int t, x, y, n;
        int itr, i, i1, i2;
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d %d %d", &x, &y, &n);
            vector<int> arr[n];
            for(itr = 0; itr < n; itr++)
            {
                scanf("%d %d %d", &i1, &i2, &i);
                arr[itr].push_back(i1);
                arr[itr].push_back(i2);
                arr[itr].push_back(i);
            }

            //The 'fflush'es are just for trial, problem persists with or without any of them
            fflush(stdout);
            vector<int> *touch_list = touch(arr, n);
            fflush(stdout);
            printf("Expected");
            fflush(stdout);
        }
    }

这是我的 input.txt

1
20 10
2
10 7 2
10 4 2

我的 output.txt 是空的。代码编译良好并且没有错误,它只是运行并完成,而不在输出文件上打印任何内容。一件奇怪的事情是,如果我从 main 中注释掉函数调用,输出会打印在 ouput.txt 上。我不明白为什么会发生这种情况,因为我认为函数内部没有任何东西可能会影响文件流。任何帮助表示赞赏,我现在完全没有想法!

4

2 回答 2

1

免责声明:这可能不是一个真实的答案,当然也不是预期的答案。但这是我在这里能做的最多的事情,它不适合评论......


是时候找一个关于 C++ 的好教程了……

这个指令很糟糕:

    vector<int>* touch_circles = (vector<int>*)malloc(sizeof(vector<int>)*size);
  1. 你不应该在 C++ 中使用 malloc,因为它只分配内存而不构造对象。你应该只使用new,甚至new只应该极其小心地使用
  2. 动态分配向量是没有意义的。向量是一个容器,负责为其将包含的对象进行动态分配
  3. 除非有特殊用例,否则应避免在 C++ 中使用原始指针。返回指向动态分配对象的指针是一种代码异味。

这还不是全部。向量是可变大小的数组。当你有一个编译时常量大小时,你应该使用std::array.

换句话说,您当前的代码始终使用错误的容器:应该使用向量的原始数组或指针,以及应该使用std::array.

这对我来说真的太糟糕了,无法理解您要做什么并帮助您修复它。请在一个新问题中用可接受的 C++ 编写它。

我不想在这里冒犯。我只是想建议你学习好的做法,因为如果你想学习 C++,这真的很重要。

于 2022-01-14T13:37:57.987 回答
0

像你这样的代码产生指向未初始化内存的指针转换为向量指针:

vector<int>* touch_circles = (vector<int>*)malloc(sizeof(vector<int>*)*size);

这只是使用此类向量的未定义行为,而且分配的内存可能不足。它可能会崩溃或挂起您的程序,并且不会产生任何输出。不要在这样的 C++ 代码中使用 malloc。如果您需要原始向量数组,请编写:

vector<int>* touch_circles = new vector<int>[size];

或者甚至更好地具有向量的向量。

于 2022-01-14T13:19:35.537 回答