第 1 章 第 1 题 高级语言的排序问题 C++标准算法实现
2024-09-08 16:09:08
问题分析
依题意,所需程序不用过多考虑效率且暗示使用库,自然想到用高级语言实现(个人选择C++)。可用顺序容器暂存数据,用标准算法解决排序问题。
代码实现
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <string> using namespace std; int main()
{
/*
* 获取数据文件名并打开文件
*/
string filename;
cout << "输入要排序的目标文件名( 当前路径下 ):";
cin >> filename;
fstream io;
io.open(filename.c_str());
if (!io) {
cout << "打开文件失败." << endl;
return ;
} /*
* 将数据从数据文件转存到顺序容器
*/
vector<int> vec;
int data;
while (io >> data)
vec.push_back(data); // 使用标准算法sort对顺序容器中的数据进行排序
sort(vec.begin(), vec.end()); // 关闭文件
io.close();
// 重置文件流
io.clear();
// 打开文件( 打开模式为删除数据文件中数据后写入 )
io.open(filename.c_str(), fstream::out|fstream::trunc); // 将排序结果写回到文件
for (vector<int>::iterator it=vec.begin(); it != vec.end(); it++)
io << *it << " "; // 关闭文件
io.close(); cout << "排序完成" << endl; return ;
}
运行测试
1. 数据文件(排序前)如下所示:
2. 编译运行:
3. 数据文件(排序后)如下所示:
小结
库和标准算法的特点就是快而方便,但在很多情况下其效率比不上结合问题实际而设计出的优质算法。
最新文章
- (十九)WebGIS中I查询的原理及设计(包含AGS、GeoServer、Supermap)
- Android学习起步 - 新建工程及相关
- VS2015如何创建单元测试并启动调试
- [WebService] the namespace on the ";definitions"; element, is not a valid SOAP version
- Cannot find class for bean with name &#39;/hello&#39; defined in ServletContext resource
- Hadoop第4周练习—HDFS读写文件操作
- Oracle触发器使用介绍
- asp.net运算符之逻辑运算符以及其他运算符
- google域名邮箱申请 gmail域名邮箱申请(企业应用套件)指南
- 根据控件Id得到控件
- Android中各种Adapter的使用方法
- Sqlserver2000联系Oracle11G数据库进行实时数据的同步
- zoj3791(An Easy Game) DP
- SQL中的join连接查询
- LoadRunner入门(一)
- android 基础03 -- Intent
- 基于Swt、ffmpeg、jacob、vlc、SApi、h2技术编写简单的旁白生成器
- WdatePicker日历添加事件,在任意月改变时处理日期事件
- Hbuilder安装
- _map
热门文章
- 瞄一眼LongAdder(jdk11)
- 【CF1023B】Pair of Toys(解方程)
- IPC 通信接口函数的名字
- hdu 1077(单位圆覆盖问题)
- Codeforces 934 C.A Twisty Movement-前缀和+后缀和+动态规划
- Codeforces 246E Blood Cousins Return(树上启发式合并)
- maven项目对于maven远程仓库没有资源的解决办法
- datetimepicker使用总结
- Go语言:变参函数
- Concurrency and Application Design (一)