Re: [問題] sort vector 問題

看板C_and_CPP作者 (髮箍)時間3年前 (2020/10/27 04:04), 3年前編輯推噓4(400)
留言4則, 3人參與, 3年前最新討論串4/6 (看更多)
※ 引述《ucrxzero (RX-0)》之銘言: : 第一點 compare function 只有在class裡面定義才需要static : 因為 sort預設是 用<比的所以拿這個舉例 : 你只會看到別人在class這樣定義 : class{ : bool operator<(Foo const& other) { } : 或 : static bool operator<(Foo const& other, Foo const& another) { } : } 以上兩者能接受的運算元型別是不同的, 這表示它們算是不同的 overloaded operator<(): struct Foo { bool operator<(const Foo&); // (1) }; bool operator<(const Foo&, const Foo&); // (2) Foo lhs, rhs; lhs < rhs; // call (1) std::as_const(lhs) < rhs; // call (2) 如果可以呼叫到不同版本, 你怎麼確定在 std::sort() 裡行為會合乎預期? : 而不是 : class{ : bool operator<(Foo const& other, Foo const& another) { } : } 如果我加上 friend 呢? 這個用法稱為 friend definition, 可將函式限定為 只能透過 ADL (Argument Dependent Lookup) 來呼叫, 避免產生額外的隱式轉 型成本, 還有其他好處在這裡就不提了. : 因為這樣會有三個東西 : a.operator<(b,c) 等於你比三個欸 : static就是沒有物件這個主人 : 順便科普一下 : static member function(用於存取static member) static member function 是在沒有物件存在的情況下, 也可以提供特定服務, 如 Meyers Singleton: class Foo { Foo(); public: static Foo& get() { static Foo foo; return foo; } int i; }; Foo::get().i = 0; 請問上面的程式碼是在存取 static data member 嗎? : static member variable (用於counter) : static global function(用於不給別的source拿來include,跟extern相反,Kernel driver常用) 你確定在寫 C++ 嗎? : static global variable(用於不給別人拿來用,extern的相反,Kernel driver常用到) 我如果用一個函式回傳參考, 這樣算不算給別人用? static int i; int& get() { return i; } : 然後static都不能遞迴 是不是有什麼魔法導致加上 static 行為就會改變? : static都要 : 都放在data segment跟著整個process的生命週期存活 : 這書上寫的 : 但是沒有初始化則放在bss而且都是零(如果像stl的string就是""空字串) 如果 std::string 沒有做 SOO (Small Object Optimzation), 那它擁有的字 元會存放在哪裡? : 第二點 這樣寫沒報錯 : #include<vector> : #include<algorithm> : using namespace std; C++ Core Guidelines SF.6: Use using namespace directives for transition, for foundation libraries (such as std), or within a local scope (only) : struct Info{ : float score; : float rank; : }; : bool comp(const Info &Info1, const Info &Infor2){ : return Info1.score>Infor2.score; : } : void MyFunction(){ : vector<Info>my; : std::sort(my.begin(), my.end(), comp); //error here : } : int main(){ : MyFunction(); : return 0; : } 雖然不知道你看的是什麼書, 但是你可能需要換一本新的 -- [P1389R1] Standing Document for SG20: Guidelines for Teaching C++ to Beginners https://wg21.link/p1389r1 SG20 Education and Recommended Videos for Teaching C++ https://www.cjdb.com.au/sg20-and-videos -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.76.216 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1603742675.A.B3A.html

10/27 14:55, 3年前 , 1F
10/27 14:55, 1F

10/27 17:36, 3年前 , 2F
我錯了嗎
10/27 17:36, 2F
因為你學習語言的方式是從結果反過來去理解特性的用法, 而不是從語言層面 去學習它的設計目的, 所以會有反客為主的結論. 從前一篇文章就可見一斑 C 跟 C++ 有規定區域物件要放在 stack 上嗎? 哪個條文這樣寫? 一旦你的學習方式這樣定型, 你寫的程式碼就不可攜, 而且是不安全的, 包含 了許多硬體資訊, 反而違背 Abstract Machine 的設計本意 ※ 編輯: loveme00835 (61.216.75.43 臺灣), 10/27/2020 18:43:08

10/27 18:59, 3年前 , 3F
推這篇
10/27 18:59, 3F

10/27 19:49, 3年前 , 4F
推推
10/27 19:49, 4F
文章代碼(AID): #1VbolJiw (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1VbolJiw (C_and_CPP)