C ++输入输出排序

时间:2015-09-08 18:21:57

标签: c++ arrays sorting templates

该作业要求使用3个输入和3个输出文件,但是现在我只尝试一个。该程序应该包含一个函数模板,按升序对值数组进行排序。该函数将接收一个无序数组并返回一个有序数组。该功能不应该执行任何输入或输出。

我的代码存在如下:

#include <iostream>
#include <iostream>
#include <fstream>
using namespace std;

ifstream inNumbers("intTestRead.txt");
ofstream outNumbers("intTestWrite.txt");

template<typename int[], typename int> void SelectionSort(int[], int);
void SelectionSort(int v[], int n)
{
    int iMin;
    for (int i = 0; i < n - 1; i++)
    {
        iMin = i;
        for (int j = i + 1; j < n; j++)
        {
            if (v[j] < v[iMin])
            {
                iMin = j;
            }
        }
     int aux = v[i];
     v[i] = v[iMin];
     v[iMin] = aux;
    }
}

void main()
{
    int data[100];
    int i;
    int length = 0;

    if (!inNumbers)
        cerr << "intTestRead.txt file could not be opened" << endl;

    for (i = 0; i < 100 && inNumbers; ++i)
    {
        inNumbers >> data[i];
        if (inNumbers)
        {
            length += 1;
        }

        SelectionSort(data, length);
        outNumbers << data[i] << endl;
    }
}

我主要使用Java编程,现在刚开始C ++让我对模板和诸如此类的东西感到困惑。分类功能由教授给我们。我的阅读文件如下:

65 40 84 9 79 90 71 93 39 44

它应该是这样的:

9 39 40 44 65 71 79 84 90 93

但看起来像这样:

65
65
84
84
84
90
90
93
93
93
-858993460

^^我知道因为我在新行中使用了endl结果,但是相同数字+ -85的多次递归让我失望。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

每次输入后都不要调用sort函数。只需在所有输入准备就绪后调用它。

类似的东西:

void main()
{
    int data[100];
    int i;
    int length = 0;

    if (!inNumbers)
        cerr << "intTestRead.txt file could not be opened" << endl;

    for (i = 0; i < 100 && inNumbers; ++i)
    {
        inNumbers >> data[i];
        if (inNumbers)
        {
            length += 1;
        }
    }

    SelectionSort(data, length);

    for (i = 0; i < length; ++i)
    {
        outNumbers << data[i] << endl;
    }
}

答案 1 :(得分:0)

再看一遍,并使用了替代方案:

#include <iostream>
#include <iostream>
#include <fstream>
#define NUMBERS 10
using namespace std;

ifstream inNumbers("intTestRead.txt");
ofstream outNumbers("intTestWrite.txt");

template <class T>
void Swap(T& A, T& B)
{
    T temp;

    temp = A;
    A = B;
    B = temp;
}

template <class T>
void SelectionSort(T A[], int N)
{
    T min;
    int j, k, minIndex;

    for (k = 0; k < N; k++) {
        min = A[k]; minIndex = k;
        for (j = k + 1; j < N; j++) {
            if (A[j] < min) { min = A[j]; minIndex = j; }
        }
        Swap(A[k], A[minIndex]);
    }
}

void main()
{
    int data[100];
    int i = 0;

    if (!inNumbers)
        cerr << "intTestRead.txt file could not be opened" << endl;

    for (i = 0; i < NUMBERS && inNumbers; ++i)
    {
        inNumbers >> data[i];
    }

    SelectionSort(data, NUMBERS);

    for (int i = 0; i < NUMBERS; ++i)
        outNumbers << data[i] << endl;
}

输入:

65 
40 
84 
9 
79 
90 
71 
93 
39 
44

输出:

9
39
40
44
65
71
79
84
90
93