读取文本文件,存储它,并按升序对该数据进行排序

Read a text file, store it, and sort this data in ascending order

本文关键字:数据 升序 排序 文件 取文本 存储 读取      更新时间:2023-10-16

您可以从标题中了解到,我在这个编程环境中确实是一个新手。我想请求你的帮助:我需要读取一个文件,比如:

11:02,11:06
15:45,16:05
...

这些数据一个在另一个之上。所以我们有11列(11个字符加上换行符)和239行。在原始文件中,它们都是随机排序的。我应该把它们按升序排序。最后,将输出可视化当然是件好事。到目前为止,我已经完成了第一步,我正在"一个字符一个字符"地读取文件。但是我不能再往下说了;我的知识不允许我那样做。如果有人能帮助我,我会非常高兴。我真的很需要这些东西

这是一个用Perl编写的数据生成器脚本;它每行生成2次,第二次总是比第一次晚:

#!/usr/bin/env perl
use strict;
use warnings;
foreach my $i (1..239)
{
    my $h1 = 10 + rand 8;
    my $h2 = $h1 + 1;
    my $m1 = rand 60;
    my $m2 = rand 60;
    printf "%.2d:%.2d,%.2d:%.2dn", $h1, $m1, $h2, $m2;
}

下面是一个比较详细的c++程序,它对perl生成的数据文件进行排序,与Unix sort程序的排序方式相同。

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
    std::vector<std::string> input;
    std::string line;
    while (std::getline(std::cin, line))
        input.push_back(line);
    std::sort(input.begin(), input.end());
    //C++03
    //for (std::vector<std::string>::iterator it = input.begin(); it != input.end(); ++it)
    //    std::cout << *it << std::endl;
    //C++11
    for (auto &it : input)
        std::cout << it << std::endl;
}

可能有一些方法可以压缩c++,但它适用于我(Mac OS X 10.8.3上的c++ 4.7.1):

    g++ -O3 -g -std=c++11 -Wall -Wextra rs.cpp -o rs

有很多方法可以压缩Perl代码。