• 第 1 章 第 1 题 高级语言的排序问题 C++标准算法实现


    问题分析

      依题意,所需程序不用过多考虑效率且暗示使用,自然想到用高级语言实现(个人选择C++)。可用顺序容器暂存数据,用标准算法解决排序问题。

    代码实现

     1 #include <iostream>
     2 #include <algorithm>
     3 #include <fstream>
     4 #include <vector>
     5 #include <string>
     6 
     7 using namespace std;
     8 
     9 int main()
    10 {
    11     /*
    12      * 获取数据文件名并打开文件
    13     */
    14     string filename;
    15     cout << "输入要排序的目标文件名( 当前路径下 ):";
    16     cin >> filename;
    17     fstream io;
    18     io.open(filename.c_str());
    19     if (!io) {
    20         cout << "打开文件失败." << endl;
    21         return 1;
    22     }
    23 
    24     /*
    25      * 将数据从数据文件转存到顺序容器
    26     */
    27     vector<int> vec;
    28     int data;
    29     while (io >> data)
    30         vec.push_back(data);
    31 
    32     // 使用标准算法sort对顺序容器中的数据进行排序
    33     sort(vec.begin(), vec.end());
    34 
    35     // 关闭文件
    36     io.close();
    37     // 重置文件流
    38     io.clear();
    39     // 打开文件( 打开模式为删除数据文件中数据后写入 )
    40     io.open(filename.c_str(), fstream::out|fstream::trunc);
    41 
    42     // 将排序结果写回到文件
    43     for (vector<int>::iterator it=vec.begin(); it != vec.end(); it++) 
    44         io << *it << " ";
    45 
    46     // 关闭文件
    47     io.close();
    48 
    49     cout << "排序完成" << endl;
    50 
    51     return 0;
    52 }

    运行测试

      1. 数据文件(排序前)如下所示:

      2. 编译运行:

     

      3. 数据文件(排序后)如下所示:

    小结

      库和标准算法的特点就是快而方便,但在很多情况下其效率比不上结合问题实际而设计出的优质算法。

      

  • 相关阅读:
    UVa 11384 Help is needed for Dexter (递归)
    HDU 4355 Party All the Time (三分求极值)
    UVa 11992 Fast Matrix Operations (线段树,区间修改)
    LA 3708 && POJ 3154 Graveyard (思维)
    LA 3942 && UVa 1401 Remember the Word (Trie + DP)
    LA 4329 Ping pong (树状数组)
    HDU 2058 The sum problem (数学+暴力)
    POJ 1458 Common Subsequence (DP+LCS,最长公共子序列)
    代理服务器
    .net垃圾回收
  • 原文地址:https://www.cnblogs.com/scut-fm/p/3234856.html
Copyright © 2020-2023  润新知