c++学习之STL中排序算法map

本文探讨了C++ STL中的map排序算法,通过一个实例展示了如何利用map统计单词词频,并按出现次数从多到少排序。当出现次数相同时,会根据字典序进行排列。

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

c++学习之STL中排序算法map

  1. 不能有关键字重复的元素
  2. 可以使用 [ ] ,下标为 关键字,返回值first和关键字相同的元素的 second
  3. 插入的元素可能失败(关键字重复的元素 )

简单算法

#include<iostream>
#include<map>
#include<string>
using namespace std;

struct Student {
    string name;
    int score;
};

Student students[5] = 
{{"Jack",77},{"Tom",64},{"xiao",99},{"Micho",89},{"Cindy",69}};
typedef map<string,int> MP;

int main(){
    MP mp;
    for(int i = 0;i<5;i++)
        mp.insert(make_pair(students[i].name,students[i].score));
    cout<< mp["Jack"] << endl;
    mp["Jack"] = 60;
    for(MP::iterator i =mp.begin();i != mp.end();i++)
        cout << "(" <<i -> first <<"," << i->second << ")" ;
         //输出所有 
    cout << endl;
    Student st ;
    st.name = "JK";
    st.score = 99;
    pair<MP::iterator,bool> p = 
                mp.insert(make_pair(st.name,st.score));//插入元素 
    if( p.second ){
        cout << "(" << p.first->first <<"," << 
                p.first->second << ") inserted." <<endl;
    }else
        cout << "inserted fair !!!" << endl;

    mp["Hali"] = 88 ; 
    // 插入一元素,其first为"Hali",然后将其second改为88; 

    MP::iterator q = mp.find("Hali");
    cout << q->first <<"," << q->second <<endl;//输出查找的值 
    return 0;
}

map例题:单词词频统计程序

输入大量单词, 每个单词一行不超过 20 字符,没有空格。 按出现次数 从多到少输这些单词及其出现次数。出现次数相同的,字典序靠前在前面
#include<iostream>
#include<map>
#include<set>
#include<string>
using namespace std;

struct Word{
    int times;
    string wd;
}; 

struct Rule{
    bool operator()(const Word &w1 , const Word &w2){
        if (w1.times != w2.times)
            return w1.times > w2.times;
        else
            return w1.wd < w2.wd; 
    }
};

int main(){
    string s;
    set<Word,Rule> st;
    map<string,int> mp;
    int t ;
    cout << "input times:";
    cin >> t; 
    while(t){
        cin >> s;
        ++ mp[s];
        t--;
    }

    for (map<string,int>::iterator i = mp.begin(); //插入到set排序
        i!= mp.end();i++){
            Word tmp;
            tmp.wd = i->first;
            tmp.times = i->second;
            st.insert(tmp);
        }
    for(set<Word,Rule>::iterator i = st.begin();
        i!=st.end();i++)
        cout << i ->wd << " " << i->times << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值