Effective STL 學習筆記:19 ~ 20

1 Item 19: 相等 (Equality) 與等價 (Equivalence)

在 STL 中, 相等 (Equality) 用於 find 算法中,一般經過 \(operator ==\) 來體現。而 等價 (Equivalence) 則常常用於排序,一般用 \(operator <\) 來體現,等價的對象不必定相等,只要他們知足知足下面條件,兩者便可視爲等價: css

\begin{cases} & !(w1 < w2)\\ & !(w2 < w1) \end{cases}

2 Item 20: Specify Comparison Type for Associative containers of pointers

對於存放指針的 Associative Containers 而言,若是咱們不指定排序算法,則默認按照 指針 大小去排,對象指針咱們沒法控制,他們在容器中的排列順序咱們也就沒法控制。若是咱們須要指定其排序順序,需本身指定 Comparison Type,例如: html

class StrLessFunctor
{
public:
    StrLessFunctor(){}
    virtual ~StrLessFunctor(){}
    bool operator()(const string* ps1, const string* ps2)
    {
        return *ps1 < *ps2;
    }
};

int main(int argc, char *argv[])
{
    set<string*, StrLessFunctor> ssp;
    ssp.insert(new string("Banana"));
    ssp.insert(new string("Orange"));
    ssp.insert(new string("Apple"));

    for_each(ssp.begin(), ssp.end(), [](string* s){cout << *s << endl;});
    return 0;
}

構造 set 時候指定的第二個模板參試不是一個函數,而是一個類型 (Comparison Type), set 會用該類型來初始化出來一個用於 sort 的函數。 java

相關文章
相關標籤/搜索