c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样

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

本文关键字:数组 一种 数据类型 排序 怎样 然后 文件 数据 读取 c++      更新时间:2023-10-16

作为工资计划的一部分,我需要对员工的净薪酬进行排序。员工的身份号码后面跟着他们的净工资。像这样:

11111 456.78
22222 891.01
33333 112.13

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

22222 891.01
11111 456.78
33333 112.13

所以基本上我需要根据他们的工资对他们进行排序,但我需要身份证号码来匹配排序后的工资。

到目前为止我的代码:

#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::sort对它们的第二个元素netpays进行排序。最后,将成对的数据写回到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而不是数组和输入数据的特定数据结构,事情就可以简化。