STL练习题:Delivery

这篇博客探讨了如何使用C++ STL来处理快递信息,包括去除冗余的'get'记录并按时间排序。通过字符串的find_first_of函数进行查找,substr函数进行切分,并利用set或map容器实现自动排序和排重功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
快递公司在运送货物的时候,会通过机器扫描得到货物信息。

但由于网络问题或重复扫描等问题,会产生冗余信息。

现在需要根据接收到的信息,进行整理并按时间排序,去除掉多余信息。

信息方式:

YYYY/MM/DD-HH:mm:ss|快递信息

要求保留某“快递信息”最早记录。

按时间顺序进行排序。

月:1-12

日:1-30

时:0-23

分、秒:0-59

输出格式

YYYY/MM/DD-HH:mm:ss : 快递信息

此题考查是查重,排序。难点在于这里需要将每个string输入拆分成两个substr分别操作。

比如输入是
2016/01/04-12:12:12|get
2016/01/04-12:23:42|get

要对get查重,而且要选择前面时间部分最早的一次记录。
这里可以用到string的find_first_of函数——str.find_first_of(“abc”)是指在str这个字符串中找”abc”,其返回的值是abc这3个字符中任何一个首次在str中出现的位置。

注意find_first_of函数和find函数的区别,如果是str.find(“abc”)的话,则必须找到完全匹配abc的才算查找成功,而find_first_of只需要abc中任何一个出现即可。

而从一个string中取出substr可以利用string的substr函数——str.substr(int pos, int count);第一个参数的意思是从某个位置pos开始取,第二个参数的意思是substr的字符个数为count个。

关于自动排序,排重等功能,可以利用set这个容器。
排重又可以利用map容器中key这个值的唯一性。

下面是解决代码:

//Delivery.hpp
#include "vector"
#include "string"
#include "map"
#include "set"
using namespace std;
vector<string> getInfoSort(vector<string> bf) {
    std::map<string, string> M;
    set<string> m;
    for (vector<string>::iterator it = bf.begin(); it != bf.end(); ++it) {
        string temp = *it;
        int off = temp.find_first_of("|");
        int count = temp.size() - off;
        string key = temp.substr(off + 1, count);
        string n_key = temp.substr(0, off);
        M.insert(make_pair(key, n_key));
        if (n_key.compare(M[key]) < 0)
            M[key] = n_key;
    }
    for (map<string,string>::iterator it = M.begin(); it != M.end(); ++it) {
        m.insert(it->second);
    }
    vector<string> afterSort;
    for (set<string>::iterator it = m.begin(); it != m.end(); ++it) {
        for (map<string,string>::iterator iter = M.begin(); iter != M.end(); ++iter) {
            if (iter->second == *it) {
                string t = iter->second;
                t += " : ";
                t += iter->first;
                afterSort.push_back(t);
            }
        }
    }
    return afterSort;
}
//client.cpp
#include <iostream>
#include <vector>
#include <string>
#include "Delivery.hpp"
 using std::string;
 int main() {
    std::vector<string> info;
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; i++) {
        std::string temp;
        std::cin >> temp;
        info.push_back(temp);
    }
      std::vector<string> afterSort = getInfoSort(info);
     for (std::vector<string>::iterator it = afterSort.begin();
         it != afterSort.end();
         ++it) {
        std::cout << *it << std::endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值