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

More than 3 years have passed since last update.

C++のstructの比較関数の書き方メモ

Last updated at Posted at 2022-03-24

メモ

Atcoderでこちらの問題を解いていた時に分からなくなったので自分用にメモ
https://atcoder.jp/contests/abc187/tasks/abc187_d

std::sort()の第3引数に比較関数を使いたかった。

実装

・2022/03/22追記
コメントで良い書き方を教えていただいたので変更

struct mydata
{
	ll score;
	ll aoki;
	ll takahasi;
};

//score, aoki, takahasiの順に昇順ソート
bool mycomp(const mydata &a, const mydata &b)
{
	if (a.score != b.score)
	{
		return a.score < b.score;
	}
	if (a.aoki != b.aoki)
	{
		return a.aoki < b.aoki;
	}
	return a.takahasi < b.takahasi;
}

int main()
{
    int N;
    cin >> N;
    vector<mydata> A(N);
    //入力とか
    sort(A.begin(), A.end(), mycomp);
}
最初のコード
struct mydata
{
	ll score;
	ll aoki;
	ll takahasi;
};

//score, aoki, takahasiの順に昇順ソート
bool mycomp(const mydata &a, const mydata &b)
{
	if (a.score < b.score)
	{
		return true;
	}
	else if (a.score == b.score && a.aoki < b.aoki)
	{
		return true;
	}
	else if(a.score == b.score && a.aoki == b.aoki && a.takahasi < b.takahasi)
	{
		return true;
	}
	return false;
}

int main()
{
    int N;
    cin >> N;
    vector<mydata> A(N);
    //入力とか
    sort(A.begin(), A.end(), mycomp);
}

備考

・mycomp()内の比較が<=ではなく, <の理由は これ??? よく分からない
http://stlalv.la.coocan.jp/sort.html

コメントでの補足

sort は同値であることをどのように判断するのでしょうか。答えは、A と B が同じであるという判断は、!(A < B) && !(B < A) で行われます。

私は違うと思います. libc++をざっと見ても同値比較している箇所はありません. 比較関数に"<="を使用すると, ソート対象に同値の値があった場合に計算回数が多くなるアルゴリズムがあるからではないでしょうか. "<="でも正しくソートされるはずです.

・tupleを使うほうが楽

2
0
3

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
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?