免费注册 查看新帖 |

Chinaunix

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

[C++] C++泛型算法的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-08-21 11:58 |只看该作者 |倒序浏览
最近在看essential C++,在linux下eclipse平台调试,尝试了书上的一个例子,但是调试总会报错,望各位大大指教。

代码如下:
  1. #include <iostream>
  2. #include<string>
  3. #include<vector>
  4. #include<algorithm>

  5. using namespace std;

  6. template <typename T>
  7. T* vfind(T *first,T *last, T value)
  8. {
  9.     if(!first||!last)
  10.     {
  11.         return 0;
  12.     }
  13.     for(;first!=last;++first)
  14.     {
  15.         if(*first==value)
  16.         {
  17.             return first;
  18.         }
  19.     }
  20.     return 0;
  21. }

  22. int main() {
  23.     int ia[5]={1,2,3,4,5};
  24.     double da[5]={1.1,2.5,3.6,4.8,5.0};
  25.     vector<int> via(ia,ia+5);
  26.     vector<double> vda(da,da+5);
  27. //    string sa[5]={"hello","hi","nihao","xiexie","over"};

  28.     int *pi=vfind(ia,ia+5,ia[1]);
  29.     double *pd=vfind(da,da+5,da[2]);

  30.     int *vpi=vfind(&via[0],&via[5],via[1]);
  31.     double *vpd=vfind(&vda[0],&vda[5],vda[1]);
  32. //    string *ps=vfind(sa,sa+5,"nihao");

  33.     cout<<"pi="<<*pi<<endl
  34.             <<"pd="<<*pd<<endl
  35.             <<"vpi="<<*vpi<<endl
  36.             <<"vpd="<<*vpd<<endl;
  37.     return 0;
  38. }
复制代码
用string类型时系统会报错,且错误很奇怪:
Description        Resource        Path        Location        Type
Invalid arguments '
Candidates are:
#0 * vfind(#0 *, #0 *, #0)
'        chapter3.cpp        /chapter3/src        line 44        Semantic Error
make: *** [src/chapter3.o] 错误 1        chapter3                         C/C++ Problem
错误:对‘vfind(std::string [5], std::string*, const char [6])’的调用没有匹配的函数        chapter3.cpp        /chapter3/src        line 44        C/C++ Problem
附注:template<class T> T* vfind(T*, T*, T)        chapter3.cpp        /chapter3/src        line 16        C/C++ Problem

请各位指教。

论坛徽章:
0
2 [报告]
发表于 2012-08-21 12:10 |只看该作者
为什么不能仔细一点呢? 模板实例化后 vfind(std::string [5], std::string*, const char [6])  已经提示出你的错误了, 而你的模板是 template<class T> T* vfind(T*, T*, T)


论坛徽章:
0
3 [报告]
发表于 2012-08-21 12:10 |只看该作者

往往会有些人, 在类似这样没弄清楚的情况下出错了, 就大呼C++是垃圾...

论坛徽章:
0
4 [报告]
发表于 2012-08-21 13:50 |只看该作者
回复 2# wgm001

谢谢您,我刚学C++,有一些错误提示还看的不是很懂,请多指教。
改为
string *ps=vfind(sa,sa+5,sa[3]); 就正确运行了。
非常感谢!
   
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP