0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

文字と整数の組のソート

Posted at

今日から学んだことのアウトプットとして記事に残そうと思います。
今回はn行続く文字と整数の組について、同じ文字があればそれらを足し合わせ最終的に降順に直し出力するというものです。

#include <iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
    int n;
    cin >> n;
    map<string, int> SD;
    for (int i = 0; i < n; ++i){
        string s;
        int d;
        cin >> s >> d;
        SD[s] += d;
    }

stringをキーとして、intを値に持つmapを作成。
文字列に対応する整数をmapに追加、すでに存在する場合、加算。

    vector<pair<int, string>> DS;
    for(auto iter = SD.begin(); iter != SD.end(); ++iter){
        DS.push_back(make_pair(iter->second, iter->first));
    }
    sort(DS.begin(),DS.end(),greater<pair<int,string>>());
    for(int i = 0; i < DS.size(); ++i){
        cout << DS[i].second << " " << DS[i].first << endl;
    }
    return 0;
}

mapの全要素をループで処理し、それぞれの要素をベクターに追加。
iter->first は文字列、iter->second は対応する整数の合計。
ソート関数で降順に並び替え、for文で結果を出力。
以上です。

マップ関数に少し苦手意識があるので改善したいと感じました。
このQiitaの記事も上手くなるために書き続けたいと思います。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?