c++读写文件和测试程序运行时间的例子

本文展示了一个使用C++对文件内容进行词频排序的例子。通过读取输入文件,利用链表存储数据,并重载比较运算符实现排序,最后将排序后的结果输出到新文件。此外,还提供了一种测量程序运行时间的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子完整代码:http://zhmster.googlepages.com/ReadFile.rar

例子功能简介:程序中google.dic是我的google输入法的词库。

本段代码功能:就是把这个文件重新按照词频排序。把词频高的放在前面。

 

代码是我一个学生作品:我做了小部分修改。

 

代码演示了如下的技术:

1. c++读写文件

2. 如何测试一个程序的运行时间。程序中calctime类可以复用。大家只要在程序开始声明一下即可。

3. 重载str_line这个类的<操作符。以此可以利用链表的排序函数来排序。

 

#include <list>
#include <string>
#include <iostream>
#include <fstream>  
#include <algorithm>
#include <stdio.h>
#include <time.h>

using namespace std;
#pragma warning ( disable : 4786 )

struct str_line
{
    string str_first;
    int int_second;
    char str_third[1000];
    bool operator < ( str_line strline_other)
    {
        if( int_second < strline_other.int_second)
            return false;
        else
            return true;
    }
} strline;

class calctime
{
public:
    clock_t start, finish;
    double duration;
    void showResult()
    {
        duration = (double)(finish - start) / CLOCKS_PER_SEC;
        printf( "%.5f seconds\n", duration );
    }
    calctime()
    {
        start = clock();
    }
    ~calctime()
    {
        finish = clock();
        showResult();
    }
};

void main()
{

        calctime calc;
        ifstream in_file("google.dic");
        ofstream out_file("out.txt");
        list<str_line> save_date_list;
        while ( in_file>>strline.str_first
            && in_file>>strline.int_second
            && in_file.getline(strline.str_third,1000))
        {
            save_date_list.push_back(strline);
        }
        save_date_list.sort();   
        list<str_line>::iterator iter = save_date_list.begin();
        for( ; iter!= save_date_list.end(); iter++ )
        {
            //str_line strlineTemp = *iter;
            out_file<< iter->str_first <<"   "
                << iter->int_second <<"   "
                << iter->str_third << "\n";   
        }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值