免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1330 | 回复: 2
打印 上一主题 下一主题

[C++] (向版主求助)初用c++标准库,请教仿函数的问题! [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-10-13 08:31 |只看该作者 |倒序浏览
我使用set作为容器存放字符串,且写了一个仿函数DSort用于set的排序,插入数据后,使用迭代器访问可以遍历容器中的内容,但find却不能成功。请高手指教!(我用VC++ 6.0 开发的)



  1. #include <map>;
  2. #include <set>;
  3. #include <vector>;
  4. #include <string>;
  5. #include <fstream>;
  6. #include <assert.h>;

  7. using namespace std;
  8. class DSort  
  9. {
  10. public:
  11.         DSort(){};
  12.         bool DSort::operator() (const string &str1 ,const string &str2) const {return str1.size() >;= str2.size() ;}
  13.         virtual ~DSort(){};                               
  14. };
  15. using namespace std;

  16. int main(int argc, char* argv[])
  17. {

  18.         set<string ,DSort>; setbydsort;
  19.         setbydsort.insert("a");
  20.         setbydsort.insert("bb");
  21.         setbydsort.insert("ccc");
  22.         set<string ,DSort>;::iterator its;
  23.         //for(its = setbydsort.begin() ; its != setbydsort.end() ; ++its)
  24.         //{
  25.         //        cout<<*its<<endl;
  26.         //}
  27.         if((its = setbydsort.find("ccc") ) != setbydsort.end())
  28.         {
  29.                 cout<<*its<<endl;
  30.         }
  31.         else
  32.         {
  33.                 cout<<"Not Find!"<<endl;
  34.         }
  35. }
复制代码

论坛徽章:
0
2 [报告]
发表于 2005-10-13 09:56 |只看该作者

(向版主求助)初用c++标准库,请教仿函数的问题!

去掉DSort中的 = 试试

论坛徽章:
0
3 [报告]
发表于 2005-10-13 10:13 |只看该作者

(向版主求助)初用c++标准库,请教仿函数的问题!

如果去掉 DSort 中

  1. return str1.size() >;= str2.size()
复制代码

判断的 “=”(
  1. return str1.size() >; str2.size()
复制代码
),那么在插入set容器时如果两个字符串长度相等,插入就会失败!
如:

  1.         setbydsort.insert("a");
  2.         setbydsort.insert("bb");
  3.         setbydsort.insert("XX");
  4.         setbydsort.insert("ccc");
复制代码

那么 “XX”就会丢失!
去掉“=”的方法好像是行不通的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP