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?

More than 3 years have passed since last update.

演算子のオーバーロード,比較関数について「個人的なメモ」

Last updated at Posted at 2021-11-13

構造体, 演算子のオーバーロード(比較)

struct Edge{
    int a, b, cost;
    bool operator<(const Edge& other) {
        return cost < other.cost;
    }
};

int main(){
    vector<Edge> v={{1,2, 3}, {2, 3, 1}, {1, 1, 0}};
    sort(v.begin(), v.end());
    for(auto e : v){
        cout << e.cost << "\n";
    }   
    return 0;
}

出力結果
構造体のメンバ変数costの昇順にソートされる.ソートの際に比較関数を用いれば同じことが出来るが,setに入れる時にはこのやり方が楽.

0
1
3

比較関数

演算子オーバーロードを使わずに構造体のメンバ変数costの昇順にソートする方法として,比較関数を用いる方法がある.出力結果は上の例と同じ.

struct Edge{
    int a, b, cost;
};

bool compare(Edge a, Edge b){
    return a.cost<b.cost;
}

int main(){
    vector<Edge> v={{1,2, 3}, {2, 3, 1}, {1, 1, 0}};
    sort(v.begin(), v.end(), compare);
    for(auto e : v){
        cout << e.cost << "\n";
    }
    return 0;
}
0
0
0

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?