簡體   English   中英

試圖使用函數對c ++中的txt文件進行排序並將其寫回到txt文件中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM