#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;
}
}