LoginSignup
39
21

More than 3 years have passed since last update.

要素がpairの時のvectorのソート

Posted at

Vectorの要素がPairの時のsort時の挙動は、
-一つ目を昇順にソートする。
-一つ目が同一の場合はさらに二つ目を昇順にソートする。

また、
降順にしたい場合はマイナスを全てに掛けておく
一つ目を昇順、二つ目を降順にしたい場合は,二つ目だけにマイナスを掛けておけば良い。

using namespace std;
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
    vector<pair<string,int>> v;
    v.push_back({ "apple",4 });
    v.push_back({ "banana",3 });
    v.push_back({ "melon",1 });
    v.push_back({ "apple",2 });
    v.push_back({ "orange",6 });

    //sort
    sort(v.begin(), v.end());

    for (auto V : v) {
        cout << V.first << " " << V.second << endl;

    }
    //apple 2
    //apple 4
    //banana 3
    //melon 1
    //orange 6

    return 0;
}
39
21
2

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
39
21