模板与迭代器

时间:2008-08-27 23:01:33   来源:论坛整理  作者:  编辑:chinaitzhe
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/





template <class elemType>

elemType min2( const vector<elemType> &vec ) {

         vector<elemType>::const_iterator iter = vec.begin();

         elemType minimum;

         if( iter < vec.end() )

            minimum = *iter;

         else

            throw "Empty vector -iterator";

         

         for(   iter; iter < vec.end();   iter )

            if( *iter < minimum )

               minimum = *iter;

         

         return minimum;

} // end of min2()





这个code在vc6,vc7下编译通过,而在dev-c 4.9.9.2下不能通过编译,提示的错误信息是:
In function `elemType min2(const std::vector <elemType, std::allocator <_CharT> >&)':`const_iterator' undeclared (first use this function)

这道题是《C primer》P58练习2.23.
我们一般认为vc6对模板支持最差,vc7稍好,dev最好,现在的情况表明这段code应该不是很符合c 标准,所以才被dev拒绝了。但是我不能从dev的错误提示信息中找到改正的方法,请各位高人指点!谢谢!
网友回复:
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/



iter < vec.end(); 


没有这种写法,只有:
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/



iter != vec.end(); 


网友回复:
引用 1 楼 yshuise 的回复:
C/C codeiter < vec.end();


没有这种写法,只有:

C/C codeiter != vec.end();


没有这种写法吗?
我按你说的改了,但是好像错误不在这里!
网友回复:
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/



#include <cstdlib>

#include <iostream>

#include <vector>

using namespace std;

template <typename T>

T min2( const vector<T> &vec ) {

     typename  vector<T>::const_iterator iter = vec.begin();

     //typename  vector<T>::value_type 

      T  minimum = *iter;

          iter  ;

         for(;iter!= vec.end(); iter  )

         if(minimum > *iter)minimum = *iter;

           

         return minimum;

} // end 

int main(int argc, char *argv[])

{

    system("PAUSE");

    return EXIT_SUCCESS;

}


网友回复:没有声明const_iterator,检查头文件
网友回复:to yshuise :谢谢你!

看来是少了关键字typename,偶在网上查了一下,这个帖子写的比较好!http://topic.csdn.net/t/20010112/21/58337.html
关键字:模板,

文章评论

共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面