Re: [問題] sort vector 問題

作者: loveme00835 (髮箍)   2020-10-27 04:04:29
※ 引述《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;
: }
雖然不知道你看的是什麼書, 但是你可能需要換一本新的
作者: F04E (Fujitsu)   2020-10-27 14:55:00
作者: ucrxzero (RX-0)   2020-10-27 17:36:00
我錯了嗎
作者: nh60211as   2020-10-27 18:59:00
推這篇
作者: ucrxzero (RX-0)   2020-10-27 19:49:00
推推
作者: CoNsTaR ((const *))   2020-11-01 23:58:00
不是啊,學習本來就是這樣 build up 的過程,要是你能夠先去了解設計目的,再去了解是怎麼達成的,那代表你本來就會了,只是需要認知和記憶而已真正的學習是你突然能夠區分你原本無法區分的概念了(可能兩個概念都可以理解,但就是無法區分),而這要能夠發生一定是因為發現了觀察的對象有行為上的不同要是每個人都可以不需要藉由寫程式和觀察程式行為來學程式語言,那我推薦不用學 C/C++ 了,直接學抽象代數、幾何學、類型論、證明論、計算理論、型式語言就好了

Links booklink

Contact Us: admin [ a t ] ucptt.com