map<string,int>

 

#include <map>
#include <string>
#include <iostream>

using namespace std;

int main() {
    map<string, string> strings;
    strings["key"] = 88;  // surprisingly compiles
    //map<string, string>::mapped_type s = 88;  // doesn't compile as expected

    cout << "Value under 'key': '" << strings["key"] << "'" << endl;

    return 0;
}

 

为什么map <string,string>接受int值作为值?

 

正常的map默认按照key值排序,而map又没有像vector一样的sort() 函数,那么如果将map按照value值排序呢?有两种方法

1. 将map中的key和value分别存放在一个pair类型的vector中,然后利用vector的sort函数排序 ~

 

C++中map按照value排序

#include <iostream>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
 
bool compare(pair<char, int> map1, pair<char, int> map2)
{
	return map1.second > map2.second;
}
 
int main()
{
	int N;
	map<char, int> map1;
	vector<pair<char, int>> buf;
	string s;
	while (cin >> N)
	{
		getchar();
		while (N--)
		{
			map1.clear();
			buf.clear();
			getline(cin, s);
			for (int i = 0; i < s.size(); i++)
			{
				map1[s[i]]++;
			}
			//实现map按照value值排序
			for (map<char, int>::iterator it = map1.begin(); it != map1.end(); it++)
			{
				buf.push_back(make_pair((*it).first, (*it).second));
			}
			sort(buf.begin(), buf.end(), compare);
			int weight = 26;
			int sum = 0;
			for (int i = 0; i < buf.size(); i++)
			{
				sum += buf[i].second*(weight--);
			}
			cout << sum << endl;
		}
	}
}

 

static bool compare(pair<QString, int> map1, pair<QString, int> map2)
{
    return map1.second > map2.second;
}

void ResultForm::MapSort()
{
    int N;

    vector<pair<QString, int> > buf;
    pair<QString, int> item;

    N = g_MapScore.size();
    buf.clear();

    //实现map按照value值排序
    for( map<QString, int>::iterator it = g_MapScore.begin(); it != g_MapScore.end(); it++ )
    {
        buf.push_back( make_pair((*it).first, (*it).second) );
    }

    std::sort( buf.begin(), buf.end(), compare );

    for( int i = 0; i < buf.size(); i++ )
    {
        item = buf[i];
        qDebug()<<item.first<<" "<<item.second;
    }
}

 

 

 

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值