96452768
V2EX  ›  C++

set 自定義函式問題

  •  
  •   96452768 · Oct 15, 2023 · 1371 views
    This topic created in 961 days ago, the information mentioned may be changed or developed.
    請問為什麼這段程式碼會輸出:8 8

    #include <iostream>
    #include <vector>
    #include <set>

    using namespace std;

    struct cmp{
    bool operator()(int a,int b){
    return a==b;
    }

    };
    int main()
    {
    vector<int> x{8,4,6,1,4,2,7,8,8,5,8,8};
    set<int,cmp> y(x.begin(),x.end());

    for(auto iter=y.begin();iter!=y.end();iter++){
    cout<<*iter<<" ";

    }
    return 0;
    }

    我知道 set 自定義函式不能這樣用,但我還是好奇這個輸出的原因,根據等於的定義是:!comp(a, b) && !comp(b, a),那這個輸出應該要是:8 8 8 8 8 吧
    lsry
        1
    lsry  
       Oct 15, 2023
    一個個插入倒是按預期的是 8 8 8 8 8 ,我覺得應該和迭代器那裏的構造函數有關係,你可以 debug 看看實現。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5683 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 01:26 · PVG 09:26 · LAX 18:26 · JFK 21:26
    ♥ Do have faith in what you're doing.