zoukankan      html  css  js  c++  java
  • Effective_STL 学习笔记(二十) 为指针的关联容器指定比较类型

    对于 string* 指针的 set,打印 set <string*> ssp 内容:

    1  for( set<string*>::const_iterator i = ssp.begin(); i != ssp.end(); i++ )
    2     cout<< *i <<endl;
    1  copy( ssp.begin(), ssp.end(), ostream_iterator<string>(cout, "
    ") );
                              // 把ssp中的字符串拷贝到 cout 内

    前一种循环的方式 *i 是指针。即使用 **i 替代,set 建立时按指针排序

    copy的方式,编译器检测到迭代器传递的 string* 与ostream_iterator 需要打印对象不匹配。

    string*  的 set 的建立:

    1   set< string*, less<string*>, allocator<string*> >  ssp;

    如果想要 string* 指针以字符串值确定顺序被存储在 set 中,不能使用默认比较仿函数类 less<string*>,必须改为自己的比较仿函数类,它的对象带有 string* 指针并按照指向的字符串值来进行排序:

    1   struct StringPtrLess: public binary_function< const string*, const string*, bool >
    2   {
    3     bool operator()( const string *ps1, const string *ps2 ) const
    4     {
    5       return *ps1 < *ps2;
    6     }
    7   };

    使用 StringPtrLess 作为 ssp 的比较类型:

    1   typedef set< string*, StringPterLess > StringPtrSet;
    2   StringPtrSet ssp;    // 建立StringPtrSet 定义的顺序排序
    3   . . .

    打印两种方式: **i 或者使用算法

    1   for( StringPtrSet::const_iterator i = ssp.begin(); i != ssp.end(); i++ )
    2     cout<< **i <<endl;
    1   void print( const string* ps )
    2   {
    3     cout<< *ps<<endl;
    4   }
    5 
    6   for_each( ssp.begin(), ssp.end(), print );

    注意到使用的 “比较类型”,是仿函数类我不是一个真正的函数,因为 set 的模板三个参数都是一种类型

    用于比较的模仿函数模板:

    1   struct DereferenceLess
    2   {
    3     template< typename PtrType >
    4     bool operator()( PtrType pT1, PtrType pT2 ) const
    5     {
    6       return *pT1 < *pT2;
    7     }
    8   };
    1   set< string*, DereferenceLess > ssp;

    本条款是关于指针的关联容器,但它也可以应用于表现为指针的对象的容器,例如,智能指针和迭代器

  • 相关阅读:
    anroid scaleType属性对应的效果
    Cannot make a static reference to the non-static method的解决方案
    Java indexOf()的两个用法
    Android关于notification的在不同API下的用法说明
    Android notification的使用介绍
    第九章 虚拟内存管理
    第八章 内存管理
    第四章 线程
    第二章 操作系统结构
    第一章 计算机系统概述
  • 原文地址:https://www.cnblogs.com/kidycharon/p/10020010.html
Copyright © 2011-2022 走看看