繁体   English   中英

C ++我需要从文件中读取数据到多维数组,然后使用一种数据类型对数组进行排序。 怎么样?

[英]c++ I need to read data from a file into a multi-dimensional array then sort the array with one data type. How?

我需要将员工的净薪金排序为薪金计划的一部分。 员工由ID号和净工资来标识。 像这样:

11111 456.78
22222 891.01
33333 112.13

我需要对数据进行排序,使其看起来像这样

22222 891.01
11111 456.78
33333 112.13

因此,基本上我需要按他们的薪水对他们进行排序,但我需要ID号以与排序后的薪水相匹配。

我到目前为止的代码:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <algorithm>

using namespace std;

/* Read data from file into array*/
int readData(long int[], double[], int);

/*print data from array unsorted*/
void printUnsorted(long int[], double, int);

/* sort items from array*/
void sort(long int[], double[], int);

/*Display sorted data to console*/
void printSorted(long int[], double, int);

void main() {

    const int MAXSIZE = 100;

    int n;
    long int id[MAXSIZE];
    double netpay[MAXSIZE];

    n = readData(id, netpay, MAXSIZE);
    printUnsorted(id, netpay);
    sort(id, netpay);
    printSorted(id, netpay);
}

int readData(long int id[], double netpay[], int n) {
    ifstream input;
    input.open("netpay.txt");
    n = 0;

    while (input >> id[n] >> netpay[n]) n++;

    input.close();
    return n;
}

void printUnsorted(long int id[], double netpay[], int n) {
    cout << "Unsorted Data" << endl;
    for (int i = 0; i < n; i++) {
        cout << id[i] << "\t" << netpay[i] << "\t" << endl;
    }


void sort(long int id[], double netpay[], int n) {
    for (int i = 0; i < n; i++) {
        sort(netpay.begin(), netpay.end()); 
    }   
}

void printSorted(long int id[], double netpay[], int n) {
    cout << "Sorted Data" << endl;
    for (int i = 0; i < n; i++) {
        cout << id[i] << "\t" << netpay[i] << "\t" << endl;
    }   
}

我知道很乱,任何人都可以向正确的方向迈出一步吗? 之后,我必须对指针执行相同的操作。

您的代码需要改进的地方很多。 您也有几个语法错误。 我建议先尝试调试代码。 但是,排序部分可以如下进行。 首先,根据数据(id,netpay)进行配对。 然后,将对保存在类似std::vector.的容器中std::vector. 接下来,使用std::sort对其对的第二个元素netpay进行排序。 最后,将成对的数据写回到idnetpay数组中。

void my_sort(int id[], double netpay[], int n) {
    typedef std::pair<int, double> data_pair_t;
    std::vector<data_pair_t> data;

    for (int i = 0; i < n; i++) {
        data.push_back(make_pair(id[i], netpay[i]));
    }

    sort(data.begin(), data.end(), [](data_pair_t a, data_pair_t b) {
        return a.second < b.second;
        } );  

    for(int i = 0; i < n; i++) {
        id[i] = data[i].first;
        netpay[i] = data[i].second;
    }
}

您可以在此处检查代码并在进行过程中对其进行扩展。 当然,如果对输入数据使用std::vector而不是数组和特定的数据结构,则可以简化事情。

暂无
暂无

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

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