天天看点

C++读写txt文件/C++生成随机数/C++记录程序运行时间

一  C++读写txt文件

写入txt文件:参考博客

逐行读取txt文件:

ifstream in;
	in.open("sample.txt", ios::in);
	if (!in.is_open())
		return 0;
	string strLine;
	double data;
	ResultSet resultset;

	while(getline(in,strLine))
	{
		istringstream istr(strLine);
		while (istr >> data)
		{
			if (resultset.size() < 10)
			{
				resultset.insert(data);
			}
			else
			{
				SetIterator iter = resultset.begin();
				if (data > *iter)
				{
					resultset.erase(iter);
					resultset.insert(data);
				}
			}
		}
		if (strLine.empty())
			continue;
	}
           

上述代码是用来逐行读取sample.txt文件然后用堆来实现从海量数据中求出Top 10(前10个最大数据)。

二 C++生成随机数

生成随机数:参考博客

ofstream out("sample.txt");
	srand((unsigned int)(time(NULL)));
	for (unsigned int i = 0; i < INT_MAX/1000; i++)
	{
		if (i!=0&&i % 30 == 0)
		{
			out << (double)rand()/32767.0* INT_MAX << endl;
		}
		else
			out << (double)rand()/32767.0 * INT_MAX << " ";
	}

	out.close();
           

上述代码是用来生成INT_MAX/1000个随机数,然后按照每行30个随机数的规则写入sample.txt文件中去。

三 C++记录程序运行时间

记录程序运行时间:参考博客

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <set>
#include <algorithm>
#include <sstream>
#include <windows.h>

using namespace std;

typedef multiset<double, less<double> > ResultSet;
typedef multiset<double, less<double> >::iterator SetIterator;

int main()
{
	clock_t startTime, endTime;
	//计时开始
	startTime = clock();

	//写入文件啊
	ofstream out("sample.txt");
	srand((unsigned int)(time(NULL)));
	for (unsigned int i = 0; i < INT_MAX/1000; i++)
	{
		if (i!=0&&i % 30 == 0)
		{
			out << (double)rand()/32767.0* INT_MAX << endl;
		}
		else
			out << (double)rand()/32767.0 * INT_MAX << " ";
	}

	out.close();

	//一行行读取文件,最终得出top 10(最大)
	ifstream in;
	in.open("sample.txt", ios::in);
	if (!in.is_open())
		return 0;
	string strLine;
	double data;
	ResultSet resultset;

	while(getline(in,strLine))
	{
		istringstream istr(strLine);
		while (istr >> data)
		{
			if (resultset.size() < 10)
			{
				resultset.insert(data);
			}
			else
			{
				SetIterator iter = resultset.begin();
				if (data > *iter)
				{
					resultset.erase(iter);
					resultset.insert(data);
				}
			}
		}
		if (strLine.empty())
			continue;
	}

	//Sleep(00000);
	
	//输出最大的100个数字
	for (SetIterator iter = resultset.begin(); iter != resultset.end(); iter++)
	{
		cout << *iter << endl;
	}

	cout << "end" << endl;   //17.964s

	//计时结束
	endTime = clock();
	cout << "The run time is: " << (double)(endTime - startTime)/CLOCKS_PER_SEC << "s!" << endl;
	return 0;
}
           

以上程序是随机生成INT_MAX/1000个随机数并按照每行30个数字写入sample文件,读取文件求取Top 10并记录程序运行时间的代码。

继续阅读