65,211
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
using namespace std;
// 生成info.txt的据程序
// info.txt中有1000万行数据
int main ()
{
char buffer[28];
clock_t start, finish;
ofstream outfile ("info.txt");
// 获取写物理文件起始时钟周期
start = clock();
for(int i = 1; i < 10000000; i++)
{
sprintf(buffer, "%d\n", i%20); // 保证只有20个不重复的数据
outfile.write (buffer, strlen(buffer));
}
// 获取写文件结束时钟周期
finish = clock();
int interval = (finish - start) * 1000 / CLOCKS_PER_SEC;
cout << "写物理文件所花时间:" << interval << "ms" << endl; // 5828ms
outfile.close();
return 0;
}
#include <iostream>
#include <fstream>
#include <map>
#include <string>
using namespace std;
// 用map的方式解决
int main(void)
{
ifstream fin("info.txt");
if(!fin)
{
cout << "can not open file..." << endl;
}
// 创建map,第一个int做为key,第二个string作为value
map<int, string> linemap;
int intkey;
string strvalue = " ";
char linestring[26];
clock_t start, finish;
// 写入linemap起始时钟周期
start = clock();
while(fin)
{
// 读取info.txt的一行,存入linestring
fin.getline(linestring, 26);
intkey = atoi(linestring);
// 将key,value对存入map中
linemap.insert(pair<int, string>(intkey, strvalue));
}
// 写入linemap结束时钟周期
finish = clock();
fin.close();
cout << (finish - start) * 1000 / CLOCKS_PER_SEC << "ms elapsed." << endl; // 7360ms
// 检查数据被插入后,是否根据strkey排序了 -> 结论:排序了
// 即使info.txt中有重复的key,也只会有第一行含有key的文本,会被读入到map中
cout << linemap.size() << endl; // 20,即只有20个不重复的数据
map<int, string>::iterator p;
for(p = linemap.begin(); p != linemap.end(); ++p)
{
cout << p->first << endl;
}
return 0;
}