c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样
c++ I need to read data from a file into a multi-dimensional array then sort the array with one data type. How?
作为工资计划的一部分,我需要对员工的净薪酬进行排序。员工的身份号码后面跟着他们的净工资。像这样:
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进行排序。最后,将成对的数据写回到id
和netpay
阵列中。
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
而不是数组和输入数据的特定数据结构,事情就可以简化。
相关文章:
- 在调用接收数组的方法时,模板化数组大小是不是一种糟糕的做法
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 寻找一种更好的方法来表示无符号字符数组
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 有没有一种惯用的方法可以在不存储变换或不必要地重新计算的情况下找到数组变换的最小/最大值?
- 我的字符串数组一次打印出前两个字符串
- void* 数组将元素转换为另一种类型
- 有没有一种方法可以获得传递给函数的数组的大小
- 如何将 numpy 二维数组作为一种可以用C++读取的二进制格式存储在磁盘上
- 我是 c++ 的新手,有没有一种算法可以找到 3d 数组中最接近的 0 的距离?
- 有没有一种递归的方式来制作这个字符串数组?
- 有没有一种方法可以接受数字数组而不接受垃圾值的输入
- 正在使用C 三元运算符中的字符串常数,一种无效的非效率数组的使用
- 一种从元组/数组获取参数包的方法
- 动态分配一维结构数组:两种方法
- 是否可以将一种类型的数组转换为大小不同的另一种类型的数组?
- 是否有一种替换C风格的Bool数组的标准方法
- 传递数组的一种病理方式:参考第一个元素
- 设置数组一次索引很多?复合文字
- 需要一种在平面表示中进行数组索引的算法