LoginSignup
2
1

More than 3 years have passed since last update.

c++/構造体のソート

Last updated at Posted at 2019-06-18

c++で構造体をソートしようとしてハマったのでメモ.

構造体を配列でまとめてソートするのではなく,
vectorに突っ込んでからソートするといい.

struct_sort.cpp
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

//構造体の定義
struct monkey {
    int w; //サルの体重
    int s; //サルのIQ
};

bool w_cmp(const struct monkey& p, const struct monkey& q) {
    return p.w < q.w;
}

bool s_cmp(const struct monkey& p, const struct monkey& q) {
    return p.s > q.s;
}

int main(void) {
    struct monkey mky[1005];
    int w, s;
    int m=0;

    std::vector<struct monkey> v;
    struct monkey temp;

    //ソートするためにvectorに突っ込む
    while(cin >> w >> s) {
        if(s == EOF) { break; }
        temp.w = w;
        temp.s = s;
        v.push_back(temp);
        m++;
    }

    //ソート(値が等しい要素の順序が維持されない)
    sort(v.begin(), v.end(), s_cmp);

    //ソート(値が等しい要素の順序が維持される)
    stable_sort(v.begin(), v.end(), w_cmp);

    //vectorの内容をすべて表示
    for(auto itr = v.begin(); itr != v.end(); ++itr) {
        cout << (*itr).w << " " << (*itr).s <<endl; 
    }
}

このプログラムに以下のような入力を与えてみる.

ipt.txt
6008 1300
6000 2100
500 2000
1000 4000
1100 3000
6000 2000
8000 1400
6000 1200
2000 1900

結果は以下のようになる.
同じ値の要素の順序が維持されている(6000の行)
(wとsをどちらもstd::sortでソートした場合は,同じ値の要素の順序が維持されず,
w=6000の要素において対応するsが降順にならない)

out.txt
500 2000
1000 4000
1100 3000
2000 1900
6000 2100
6000 2000
6000 1200
6008 1300
8000 1400
2
1
5

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
2
1