1. 程式人生 > >C++ STL set::find的用法

C++ STL set::find的用法

參考:

http://blog.csdn.net/lihao21/article/details/6302196

/* class for function predicate
    * - operator() returns whether a person is less than another person
    */
   class PersonSortCriterion {
     public:
       bool operator() (const Person& p1, const Person& p2) const {
           /* a person is less than another person
            * - if the last name is less
            * - if the last name is equal and the first name is less
            */
           return p1.lastname()<p2.1astname() ||
                  (! (p2.1astname()<p1.lastname()) &&
                   p1.firstname()<p2.firstname());
       }
   };

set的find查詢相等原理

http://bbs.csdn.net/topics/390237400

向set中新增的元素型別必須過載<操作符用來排序。排序滿足以下準則: 
1、非對稱,若A<B為真,則B<A為假。 
2、可傳遞,若A<B,B<C,則A<C。 
3、A<A永遠為假。 
set中判斷元素是否相等: 
if(!(A<B || B<A)),當A<B和B<A都為假時,它們相等。

以上好處可以直接不通過指標而通過物件來查詢

class  Data
{
public:
    Data(int view, const char* key)
        : view_(view),
        key_(key),
        data_(NULL) {}
    ~Data() {}

public:
    int view_;
    const char* key_;
    void* data_;
};

class DataComparator {
public:
    bool operator()(const Data* d1, const Data* d2) const {
        return (d1->view_ == d2->view_) ? (d1->key_ < d2->key_) :
            (d1->view_ < d2->view_);
    }
};


 typedef std::set<Data*, DataComparator> DataSet;

void main() 
{ 
    DataSet dataSet;
    dataSet.insert(new Data(1,"b"));
    DataSet::iterator iter=dataSet.find(n