[英]trying to sort a txt file in c++ using a function and writing it back out to a txt file
void insertionSort (int arrtosort[], int size)
{
int temp = arrtosort[0];
for(int i = 1; i < size; i++)
{
temp = arrtosort[i];
int j = 0;
for(j = i; j > 0; j--)
if(temp < arrtosort[j - 1])
arrtosort[j] = arrtosort[j - 1];
else break;
arrtosort[j-1] = temp;
}
}
我正在尝试使用此排序功能对案例内部的txt文件进行排序。
我试过的是
case 1:
insertionSort(fileid,SIZE);
ingrades.open("dataout.txt");
for (idx=0;idx<SIZE;idx++)
{
int id,n_grade;
string l_grade;
ingrades>>id>>n_grade>>l_grade;
for(int i=0;i<SIZE;i++)
{
if(fileid[i]==id)
{
out.open("data.txt");
out<<id<<" "<<n_grade<<" "<<l_grade<<endl;
out.close();
}
}
}
ingrades.close();
break;
我尝试使用此代码进行各种变体,不仅是将其写入txt文件,还只是将其显示在控制台中
14731 4
15960 6
15517 8
16638 1
34974 6
32684 4
35157 2
33904 4
23132 7
37344 3
这些是我尝试在程序字母中排序的数字,因此在达到要求之前,已将其成绩写给它。 我正在尝试使用该功能对文件进行排序并将其写到txt文件中,或者只是在控制台上显示所有帮助。
另一个问题是,当我使用该函数时,我似乎一遍又一遍地获得相同的数字,好像其余的全部被删除并由最大的数字代替
读取文件,将键值对存储到std :: map中,然后从头到尾迭代该映射,并将其内容写入文件。
诀窍是std :: map会自动为您排序数据,甚至可以指定一个比较器!
地图根据其键进行排序。
如果您只想对数字排序,请参见cplusplus.com中的示例
// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
输出:
myvector contains: 12 26 32 33 45 53 71 80
如果您想要更多的值,只需std::pair<int,int>
向量使用std::pair<int,int>
并创建自己的比较函数,如示例中所示。
bool myfunction (std::pair<int,int> i,std::pair<int,int> j) { return (i.first<j.first); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.