我辈岂是蓬蒿人!

C++ && keyWordSpotting

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  11 Posts :: 0 Stories :: 4 Comments :: 0 Trackbacks

常用链接

留言簿(9)

我参与的团队

搜索

  •  

积分与排名

  • 积分 - 6886
  • 排名 - 1379

最新评论

阅读排行榜

评论排行榜

2006年8月29日 #

 

 1 #ifndef _GHH_TIMER_GHH_
 2 #define _GHH_TIMER_GHH_    1
 3 
 4 // File: ghhTimer.h
 5 // Date: 2006.08.14
 7 
 8 #include <ctime>
 9 
10 // 类导出导入类别的符号定义
11 #ifdef _DLL_FILE_
12 #define PORTTYE __declspec(dllexport) // 导出
13 #else
14 #define PORTTYE __declspec(dllimport) // 导入
15 #endif    // end of _DLL_FILE_
16 
17 /****************************************************************************
18  * 类名称    ghhTimer
19  * 
20  * 描述
21  *    本类对标准库计时函数进行了封装,可以实现非常精确的计时,毫秒级别
22  *
23  * 使用说明
24  *    在所要计时程序段之前,调用Start函数,程序段结束时,调用Pause函数,
25  *    多次调用程序段,即可以比较精确的估计程序段的运行时间
26 ****************************************************************************/
27 class  PORTTYE ghhTimer
28 {
29 public:
30     ghhTimer();
31 
32 public:
33     bool Start(void); 
34     bool Stop(void);    
35     bool Pause(void);
36     size_t GetSeconds(voidconst;
37     size_t GetMiliSeconds(voidconst;
38 
39 private:
40     enum {run = 1, stop, pause} _Status;
41     time_t _Clock;
42     time_t _TotalClocks;
43 };
44 
45 #endif // end of _GHH_TIMER_GHH_

  1 #ifndef _DLL_FILE_
  2 #define _DLL_FILE_
  3 #endif
  4 #include "ghhTimer.h"
  5 
  6 /****************************************************************************
  7  * about the important function "clock()"
  8  * #include <time.h>
  9  * clock_t clock( void );
 10  * The clock() function returns the processor time since the program started, 
 11  * or -1 if that information is unavailable. 
 12  * To convert the return value to seconds, divide it by CLOCKS_PER_SEC. 
 13  * (Note: if your compiler is POSIX compliant, 
 14  * then CLOCKS_PER_SEC is always defined as 1000000.)
 15  ***************************************************************************/
 16 
 17 
 18 // 构造函数,设置初始状态
 19 ghhTimer::ghhTimer() : _Status(stop), _Clock(0), _TotalClocks(0)
 20 {
 21 }
 22 
 23 // 当表已经停止或者暂停时启动停表,成功返回true,否则返回false
 24 bool ghhTimer::Start(void)
 25 {
 26     switch (_Status)
 27     {
 28     case stop :
 29         _TotalClocks = 0;
 30         _Clock = clock();
 31         break;
 32 
 33     case pause :
 34         _Clock = clock();
 35         break;
 36 
 37     case run :
 38         break;
 39 
 40     default :
 41         return false;
 42     }
 43 
 44     _Status = run;
 45 
 46     return true;
 47 }
 48 
 49 // 表运行时暂停计时,成功返回true,否则返回false
 50 bool ghhTimer::Pause(void)
 51 {
 52     switch (_Status)
 53     {
 54     case stop :
 55     case pause :
 56         break;
 57 
 58     case run :
 59         _TotalClocks += (clock() - _Clock);
 60         _Clock = 0;
 61         _Status = pause;
 62         break;
 63 
 64     default :
 65         return false;
 66     }
 67 
 68     return true;
 69 }
 70 
 71 // 表运行或暂停时停止计时
 72 bool ghhTimer::Stop(void)
 73 {
 74     switch (_Status)
 75     {
 76     case stop :
 77     case pause :
 78         break;
 79         
 80     case run :
 81         _TotalClocks +=(clock() - _Clock);
 82         _Clock = 0;
 83         break;
 84 
 85     default :
 86         return false;
 87     }
 88 
 89     _Status = stop;
 90     
 91     return true;
 92 }
 93 
 94 // 得到当前积累的秒数
 95 size_t ghhTimer::GetSeconds(voidconst
 96 {
 97     time_t Clocks;
 98 
 99     switch (_Status)
100     {
101     case stop:
102     case pause:
103         Clocks = _TotalClocks;
104         break;
105 
106     case run:
107         Clocks = _TotalClocks + clock() - _Clock;
108         break;
109 
110     default:
111         return false;
112     }
113     return (Clocks / CLOCKS_PER_SEC);
114 }
115 
116 // 得到当前积累的毫秒数
117 size_t ghhTimer::GetMiliSeconds(voidconst
118 {
119     time_t Clocks;
120 
121     switch(_Status)
122     {
123     case stop:
124     case pause:
125         Clocks = _TotalClocks;
126         break;
127     case run:
128         Clocks = _TotalClocks + clock() - _Clock;
129         break;
130 
131     default:
132         return false;
133     }
134     return (Clocks * 1000 / CLOCKS_PER_SEC);
135 }
136 
posted @ 2006-08-29 09:51 keyws 阅读(919) | 评论 (0)编辑 收藏

2006年8月22日 #

Shifting from C to C++

1. To C++ programmer, for example, a pointer to a pointer looks a little funny. Why, we wonder, wasn’t a reference to a pointer used  instead?

       const char chr[] = "chenzhenshi&guohonghua";

       const char*  pchr = chr;

       const char** ppchr = &pchr;

       const char*&  rpchr  = pchr; // a reference to a pointer

       std::cout << pchr << ' ' << *ppchr << ' ' << rpchr << std::endl;

 

2. C is a fairly simple language. All it really offers is macros, pointers, structs, arrays, and functions. No matter what the problem is, the solution will always boil down to macros, pointers, structs, arrays, and functions. Not so in C++. The macros, pointers, structs, arrays and functions are still there, of course, but so are private and protected members, function overloading, default parameters, constructors and destructors, user-defined operators, inline functions, references, friends, templates, exceptions, namespaces, and more. The design space is much richer in C++ than it is in C: there are just a lot more options to consider.

Item 1: Prefer const and inline to #define

3. The Item might better be called “prefer the compiler to the preprocessor”.

4.    const char* pc;

       pc = a1;

       std::cout << pc << std::endl;

       pc = a2;

       std::cout << pc << std::endl;

 

       const char* const pcc = "a const pointer to a const char array";

       std::cout << pcc << std::endl;

       // error C2166: l-value specifies const object

       // pcc = a1;  // error!

       std::cout << pcc << std::endl;

5. You can define a const variable in a class, but it must be static const, and have a definition in an implementation file.

// .h file

class try_const

{

public:

       static const int num;

};

// .cxx file

const int try_const::num = 250;

6. You can get all the efficiency of a macro plus all the predictable behavior and type safety of a regular function by using an inline function.

Template <class type>

Inline const type& max (const type& a, const type& b)

{

Return a > b ? a : b ;

}

7. Given the availability of consts and inlines, your need for the preprocessor is reduced, but it's not completely eliminated. The day is far from near when you can abandon #include, and #ifdef/#ifndef continue to play important roles in controlling compilation. It's not yet time to retire the preprocessor, but you should definitely plan to start giving it longer and more frequent vacations.

Item 2: Prefer <iostream> to <stdio.h>

8.  scanf and printf are not type-safe and extensible.

9.  In particular, if you #include <iostream>, you get the elements of the iostream library ensconced within the namespace std (see Item 28), but if you #include <iostream.h>, you get those same elements at global scope. Getting them at global scope can lead to name conflicts, precisely the kinds of name conflicts the use of namespaces is designed to prevent.

Item 3: Prefer new and delete to malloc and free

10. The problem with malloc and free(and their variants) is simple : they don’t know about constructors and destructors.

11. free 操作不会调用析构函数,如果指针所指对象本身又分配了内存,则会造成内存丢失。

Item 4: Prefer C++ style comments

Memory Management

12. Memory management concerns in C++ fall into two general camps: getting it right and making it perform efficiently.

Item 5: Use the same form in corresponding uses of new and delete

13. When you use new, two things happen. First, memory is allocated. Second, one or more constructors are called for that memory. When you use delete, two other things happen: one or more destructors are called for the memory, then the memory is deallocated.

14. The standard C++ library includes string and vector templates that reduce the need for built-in arrays to nearly zero.

Item 6: Use delete on pointer members in destructors

15. Speaking of smart pointers, one way to avoid the need to delete pointer members is to replace those members with smart pointer objects like the standard C++ Library’s auto_ptr.

Item 7: Be prepared for out-of-memory conditions

Item 8: Adhere to convention when writing operator new and operator delete

Item 9: Avoid hiding the “normal” form of new

Item 10: Write operator delete if you write operator new

让我们回过头去看看这样一个基本问题:为什么有必要写自己的 operator new operator delete ?答案通常是:为了效率。缺省的 operator new operator delete 具有非常好的通用性,它的这种灵活性也使得在某些特定的场合下,可以进一步改善它的性能。尤其在那些需要动态分配大量的但很小的对象的应用程序里,情况更是如此。

 

posted @ 2006-08-22 17:24 keyws 阅读(497) | 评论 (0)编辑 收藏

  
   动态分配的对象:程序员完全控制分配与释放,分配在程序的空闲存储区(free store)的可用内存池中。
 
 1
)单个对象的动态分配与释放;
 new
表达式没有返回实际分配的对象,而是返回指向该对象的指针。对该对象的全部操作都要通过这个指针间接完成。
 
随机分配的内存具有随机的位模式,建议初始化,例如:

 int* pi = new int(0);


 

空闲存储区是有限的资源,若被耗尽,new表达式会失败,抛出bad_alloc异常。
 
这样做没有必要:

     if  ( pi != 0 )
        delete pi;

  说明:如果指针操作数被设置为0,则C++保证delete表达式不会调用操作符delete()。所以没有必要测试其是否为0
 
delete表达式之后,pi被称作空悬指针,即指向无效内存的指针。空悬指针是程序错误的根源,建议对象释放后,将该指针设置为0
 
 2
auto_ptr
 auto_ptr
C++标准库提供的类模板,它可以帮助程序员自动管理用new表达式动态分配的单个对象,但是,它没有对数组管理提供类似支持。它的头文件为:
 

    #include  < memory >  

  auto_ptr对象的生命期结束时,动态分配的对象被自动释放。
 auto_ptr
类模板背后的主要动机是支持与普通指针类型相同的语法,但是为auto_ptr对象所指对象的释放提供自动管理。例:

     //  第一种初始化形式
    std::auto_ptr< int > pi(  new   int (1024) );     // 

 auto_ptr 类模板支持所有权概念,当一个auto_ptr对象被用另一个auto_ptr对象初始化赋值时,左边被赋值或初始化的对象就拥有了空闲存储区内底层对象的所有权,而右边的auto_ptr对象则撤消所有责任。例:

    std::auto_ptr<std:: string > pstr_auto(  new  std:: string ( "Brontonsaurus" ) );
    
// 
第二种初始化形式
    std::auto_ptr<std:: string > pstr_auto2( pstr_auto );

  判断是否指向一个对象,例:

     //  第三种初始化形式
    auto_ptr < int >  p_auto_int;    
    
if  ( p_auto_int. get ()  ==   0  )
        
    
else
        
//  重置底层指针,必须使用此函数        
        p_auto_int.reset(  new   int 1024  ) );


 3)数组的动态分配与释放
 
建议使用C++标准库string,避免使用C风格字符串数组。
 
为避免动态分配数组的内存管理带来的问题,一般建议使用标准库vectorliststring容器类型。
 
 4
)常量对象的动态分配与释放
 
可以使用new表达式在空闲存储区内创建一个const对象,例:

     //  此时必须初始化,否则编译错误
     const   int * pci =  new   const   int (1024);    

  我们不能在空闲存储区创建内置类型元素的const数组,原因是:我们不能初始化用new表达式创建的内置类型数组的元素。例:

     const   int * pci =  new   const   int [100];  //  编译错误


 5
)定位new表达式
 new
表达式的第三种形式允许程序员要求将对象创建在已经被分配好的内存中。称为:定位new表达式(placement new expression)。程序员在new表达式中指定待创建对象所在的内存地址。如下所示:
 new
place_address) type-specifier
 
注意:place_address必须是个指针,必须包含头文件<new>。这项设施允许程序员预分配大量的内存,供以后通过这种形式的new表达式创建对象。例如:

    #include  < iostream >
    #include 
< new >      //  必须包含这个头文件
    
    
const   int  chunk  =   16 ;
    
class  Foo
    
{
        
    }
;
    
    
char *  buf  =   new   char sizeof (Foo)  *  chunk ];
    
    
int  main( int  argc,  char *  argv[])
    
{
        
//  只有这种形式的创建,没有配对形式的delete 
        Foo *  pb  =   new  (buf) Foo;
                
        delete[] buff;
        
        
return   0 ;
    }

posted @ 2006-08-22 14:54 keyws 阅读(576) | 评论 (3)编辑 收藏

2006年8月20日 #

Introduction

1. A declaration tells compilers about the name and type of an object, function, class, or template, but it omits certain details.

2. A definition, on the other hand, provides compilers with the details. For an object, the definition is where compilers allocate memory for the object. For a function or a function template, the definition provides the code body. For a class or a class template, the definition lists the members of the class or template.

3. When you define a class, you generally need a default constructor if you want to define arrays of objects.Incidentally, if you want to create an array of objects for which there is no default constructor, the usual ploy is to define an array of pointers instead. Then you can initialize each pointer separately by using new.

4. Probably the most important use of the copy constructor is to define what it means to pass and return objects by value.

5. From a purely operational point of view, the difference between initialization and assignment is that the former is performed by a constructor while the latter is performed by operator=. In other words, the two processes correspond to different function calls. The reason for the distinction is that the two kinds of functions must worry about different things. Constructors usually have to check their arguments for validity, whereas most assignment operators can take it for granted that their argument is legitimate (because it has already been constructed). On the other hand, the target of an assignment, unlike an object undergoing construction, may already have resources allocated to it. These resources typically must be released before the new resources can be assigned. Frequently, one of these resources is memory. Before an assignment operator can allocate memory for a new value, it must first deallocate the memory that was allocated for the old value.

//  a possible String constructor
String::String( const   char   * value)
{
    
if  (value)
    

        
//  if value ptr isn't null
        data  =   new   char [strlen(value)  +   1 ];
        strcpy(data,value);
    }
    
    
else  
    

        
//  handle null value ptr3
        data  =   new   char [ 1 ];
        
* data  =   ' \0 ' //  add trailing
         null   char
    }

}


//  a possible String assignment operator

String
&  String:: operator = ( const  String &  rhs)
{
    
if  ( this   ==   & rhs)
        
return   * this //  see Item 17

    delete [] data; 
//  delete old memory
    
    data 
=   //  allocate new memory
         new   char [strlen(rhs.data)  +   1 ];

    strcpy(data, rhs.data);
    
    
return   * this //  see Item 15
}


6. These different casting forms serve different purposes:

const_cast is designed to cast away the constness of objects and pointers, a topic I examine in Item 21.

dynamic_cast is used to perform "safe downcasting," a subject we'll explore in Item 39.

reinterpret_cast is engineered for casts that yield implementation-dependent results, e.g., casting between function pointer types. (You're not likely to need reinterpret_cast very often. I don't use it at all in this book.)

static_cast is sort of the catch-all cast. It's what you use when none of the other casts is appropriate. It's the closest in meaning to the conventional C-style casts.

posted @ 2006-08-20 16:10 keyws 阅读(321) | 评论 (0)编辑 收藏

2006年8月17日 #

     摘要: Thinking in C++, 2nd ed. Volume 1 ©2000 by Bruce Eckel Unary operators The following example shows the syntax to overload all the unary operators, ...  阅读全文
posted @ 2006-08-17 12:14 keyws 阅读(597) | 评论 (0)编辑 收藏

2006年8月16日 #

   学习数据结构,用到了输入输出运算符重载,结果编译之下,错误重重,,随即停止学习进度,追查祸源,在花费巨大脑力与时间成本之后,终于知自己错误之所在,定位于名字空间之困扰。为牢记教训,写一简化版本记录 debug 过程如下,警示自己。

问题
   

   有如下两个代码文件:
   // 20060816_operator.cxx

 1 #include <iostream>
 2 using namespace std;
 3 #include "20060816_operator.h"
 4 int main(int argc, char* argv[])
 5 {
 6     const std::string GHH("GuoHonghua");
 7     Honghua ghh(GHH);
 8     cout << ghh << endl;
 9     return 0;
10 }
   

// 20060816_operator.h

 1 #ifndef _20060816_OPERATOR_GHH_
 2 #define _20060816_OPERATOR_GHH_    1
 3 
 4 // Author : GuoHonghua
 5 // Date : 2006.08.16
 6 // File : 20060816_operator.h
 7 
 8 #include <iostream>
 9 #include <string>
10 class Honghua
11 {
12     friend std::ostream& operator<<(std::ostream& os, const Honghua& ghh);
13 public:
14     Honghua(const std::string& ghh) : _ghh(ghh)
15     {
16     }
17 
18 private:
19     std::string _ghh;
20 };
21 
22 std::ostream& operator<<(std::ostream& os, const Honghua& ghh)
23 {
24     os << ghh._ghh;
25     return os;
26 }
27 
28 #endif // end of _20060816_OPERATOR_GHH_

用上面两个文件建立工程,vc6.0下编译会出错。报告如下:

--------------------Configuration: 20060816_operator - Win32 Debug--------------------

Compiling...

20060816_operator.cxx

f:\ghh_project\cxxdetail\20060816_operator.h(24) : error C2248: '_ghh' : cannot access private member declared in class 'Honghua'

        f:\ghh_project\cxxdetail\20060816_operator.h(19) : see declaration of '_ghh'

F:\ghh_project\CxxDetail\20060816_operator.cxx(8) : error C2593: 'operator <<' is ambiguous

Error executing cl.exe.

 

20060816_operator.exe - 2 error(s), 0 warning(s)
解决:
   

1.  调整名字空间声明和自定义头文件的次序,如下:

1 #include <iostream>
2 #include "20060816_operator.h"
3 using namespace std;
4 int main(int argc, char* argv[])
5 

2.  把类定义于标准名字之内,20060816_operator.h文件修改如下(不推荐)

 1 #ifndef _20060816_OPERATOR_GHH_
 2 #define _20060816_OPERATOR_GHH_    1
 3 
 4 // Author : GuoHonghua
 5 // Date : 2006.08.16
 6 // File : 20060816_operator.h
 7 
 8 #include <iostream>
 9 #include <string>
10 namespace std
11 {
12     class Honghua
13     {
14         friend std::ostream& operator<<(std::ostream& os, const Honghua& ghh);
15     public:
16         Honghua(const std::string& ghh) : _ghh(ghh)
17         {
18         }
19         
20     private:
21         std::string _ghh;
22     };
23     
24     
25     std::ostream& operator<<(std::ostream& os, const Honghua& ghh)
26     {
27         os << ghh._ghh;
28         return os;
29     }
30 }
31 #endif // end of _20060816_OPERATOR_GHH_ 

3.  使用头文件iostream.h代替iostream,比较落后的方式(不推荐!

 1 // 20060816_operator.cxx
 2 // #include <iostream>
 3 #include <iostream.h>
 4 #include <iostream.h>
 5 #include "20060816_operator.h"
 6 int main(int argc, char* argv[])
 7 {
 8     const std::string GHH("GuoHonghua");
 9     Honghua ghh(GHH);
10     cout << ghh << endl;
11     return 0;
12 } 

 1 // 20060816_operator.h
 2 #ifndef _20060816_OPERATOR_GHH_
 3 #define _20060816_OPERATOR_GHH_    1
 4 
 5 // Author : GuoHonghua
 6 // Date : 2006.08.16
 7 // File : 20060816_operator.h
 8 // #include <iostream>
 9 #include <iostream.h>
10 #include <string>
11 
12 class Honghua
13 {
14     friend ostream& operator<<(ostream& os, const Honghua& ghh);
15 public:
16     Honghua(const std::string& ghh) : _ghh(ghh)
17     {
18     }
19     
20 private:
21     std::string _ghh;
22 };
23 
24 
25 ostream& operator<<(ostream& os, const Honghua& ghh)
26 {
27     os << ghh._ghh;
28     return os;
29 }
30 
31 #endif // end of _20060816_OPERATOR_GHH_

4.  任何时候都不使用using namespace 声明!这是只需要修改20060816_operator.cxx文件如下:

 1 #include <iostream>
 2 #include "20060816_operator.h"
 3 int main(int argc, char* argv[])
 4 {
 5     // const string GHH("GuoHonghua");
 6     const std::string GHH("GuoHonghua");
 7     Honghua ghh(GHH);
 8     // cout << ghh << endl;
 9     std::cout << ghh << std::endl;
10     return 0;
11 }

体会
   名字空间本来就是为了解决名字冲突问题而引入,以使标准库不受外界影响。在这个意义上来说,
using namespace std;不是可以随意使用的语句,应该考虑到它的位置对程序的可能影响,而最彻底的杜绝错误的解决办法是在任何时候任何情况下都不使用此语句!

posted @ 2006-08-16 21:09 keyws 阅读(391) | 评论 (0)编辑 收藏

2006年8月13日 #

Syntax:
														
1 #include <vector>
2 void assign( size_type num, const TYPE& val );
3 void assign( input_iterator start, input_iterator end );

The assign() function either gives the current vector the values from start to end, or gives it num copies of val.

This function will destroy the previous contents of the vector.

For example, the following code uses assign() to put 10 copies of the integer 42 into a vector:

 vector<int> v;
 v.assign( 10, 42 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << v[i] << " ";
 }
 cout << endl;            

The above code displays the following output:

 42 42 42 42 42 42 42 42 42 42          

The next example shows how assign() can be used to copy one vector to another:

 vector<int> v1;
 for( int i = 0; i < 10; i++ ) {
   v1.push_back( i );
 }              

 vector<int> v2;
 v2.assign( v1.begin(), v1.end() );             

 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;            

When run, the above code displays the following output:

 0 1 2 3 4 5 6 7 8 9

back
Syntax:
				
1 #include <vector>
2 TYPE& back();
3 const TYPE& back() const;

The back() function returns a reference to the last element in the vector.

For example:

 vector<int> v;
 for( int i = 0; i < 5; i++ ) {
   v.push_back(i);
 }
 cout << "The first element is " << v.front()
      << " and the last element is " << v.back() << endl;           

This code produces the following output:

 The first element is 0 and the last element is 4               


at
Syntax:
  #include <vector>
  TYPE& at( size_type loc );
  const TYPE& at( size_type loc ) const;

The at() function returns a reference to the element in the vector at index loc. The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the vector.

For example, consider the following code:

 vector<int> v( 5, 1 );
 for( int i = 0; i < 10; i++ ) {
   cout << "Element " << i << " is " << v[i] << endl;
 }              

This code overrunns the end of the vector, producing potentially dangerous results. The following code would be much safer:

 vector<int> v( 5, 1 );
 for( int i = 0; i < 10; i++ ) {
   cout << "Element " << i << " is " << v.at(i) << endl;
 }              

Instead of attempting to read garbage values from memory, the at() function will realize that it is about to overrun the vector and will throw an exception.

capacity
Syntax:
  #include <vector>
  size_type capacity() const;

The capacity() function returns the number of elements that the vector can hold before it will need to allocate more space.

For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size, the other method calls the reserve function to achieve a similar goal:

 vector<int> v1(10);
 cout << "The capacity of v1 is " << v1.capacity() << endl;
 vector<int> v2;
 v2.reserve(20);
 cout << "The capacity of v2 is " << v2.capacity() << endl;         

When run, the above code produces the following output:

 The capacity of v1 is 10
 The capacity of v2 is 20               

C++ containers are designed to grow in size dynamically. This frees the programmer from having to worry about storing an arbitrary number of elements in a container. However, sometimes the programmer can improve the performance of her program by giving hints to the compiler about the size of the containers that the program will use. These hints come in the form of the reserve() function and the constructor used in the above example, which tell the compiler how large the container is expected to get.

The capacity() function runs in constant time.


begin
Syntax:
  #include <vector>
  iterator begin();
  const_iterator begin() const;

The function begin() returns an iterator to the first element of the vector. begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

   // Create a list of characters
   list<char> charList;
   for( int i=0; i < 10; i++ ) {
     charList.push_front( i + 65 );
   }
   // Display the list
   list<char>::iterator theIterator;
   for( theIterator = charList.begin(); theIterator != charList.end(); theIterator++ ) {
     cout << *theIterator;
   }            
max_size
Syntax:
  #include <vector>
  size_type max_size() const;

The max_size() function returns the maximum number of elements that the vector can hold. The max_size() function should not be confused with the size() or capacity() functions, which return the number of elements currently in the vector and the the number of elements that the vector will be able to hold before more memory will have to be allocated, respectively.

clear
Syntax:
  #include <vector>
  void clear();

The function clear() deletes all of the elements in the vector. clear() runs in linear time.

empty
Syntax:
  #include <vector>
  bool empty() const;

The empty() function returns true if the vector has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a vector and display its contents in reverse order:

 vector<int> v;
 for( int i = 0; i < 5; i++ ) {
   v.push_back(i);
 }
 while( !v.empty() ) {
   cout << v.back() << endl;
   v.pop_back();
 }              
end
Syntax:
  #include <vector>
  iterator end();
  const_iterator end() const;

The end() function returns an iterator just past the end of the vector.

Note that before you can access the last element of the vector using an iterator that you get from a call to end(), you'll have to decrement the iterator first. This is because end() doesn't point to the end of the vector; it points just past the end of the vector.

For example, in the following code, the first "cout" statement will display garbage, whereas the second statement will actually display the last element of the vector:

  vector<int> v1;
  v1.push_back( 0 );
  v1.push_back( 1 );
  v1.push_back( 2 );
  v1.push_back( 3 );

  int bad_val = *(v1.end());
  cout << "bad_val is " << bad_val << endl;

  int good_val = *(v1.end() - 1);
  cout << "good_val is " << good_val << endl;

The next example shows how begin() and end() can be used to iterate through all of the members of a vector:

 vector<int> v1( 5, 789
  ); vector<int>::iterator it; for( it = v1.begin(); it !=
  v1.end(); it++ ) { cout << *it << endl; } 

The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

end() runs in constant time.


erase
Syntax:
  #include <vector>
  iterator erase( iterator loc );
  iterator erase( iterator start, iterator end );

The erase() function either deletes the element at location loc, or deletes the elements between start and end (including start but not including end). The return value is the element after the last element erased.

The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, dequeues, and strings. The multiple-element version of erase always takes linear time.

For example:

 // Create a vector, load it with the first ten characters of the alphabet
 vector<char> alphaVector;
 for( int i=0; i < 10; i++ ) {
   alphaVector.push_back( i + 65 );
 }
 int size = alphaVector.size();
 vector<char>::iterator startIterator;
 vector<char>::iterator tempIterator;
 for( int i=0; i < size; i++ ) {
   startIterator = alphaVector.begin();
   alphaVector.erase( startIterator );
   // Display the vector
   for( tempIterator = alphaVector.begin(); tempIterator != alphaVector.end(); tempIterator++ ) {
     cout << *tempIterator;
   }
   cout << endl;
 }              

That code would display the following output:

 BCDEFGHIJ
 CDEFGHIJ
 DEFGHIJ
 EFGHIJ
 FGHIJ
 GHIJ
 HIJ
 IJ
 J              

In the next example, erase() is called with two iterators to delete a range of elements from a vector:

 // create a vector, load it with the first ten characters of the alphabet
 vector<char> alphaVector;
 for( int i=0; i < 10; i++ ) {
   alphaVector.push_back( i + 65 );
 }
 // display the complete vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;            

 // use erase to remove all but the first two and last three elements
 // of the vector
 alphaVector.erase( alphaVector.begin()+2, alphaVector.end()-3 );
 // display the modified vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;            

When run, the above code displays:

 ABCDEFGHIJ
 ABHIJ          

front
Syntax:
  #include <vector>
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the vector, and runs in constant time.


insert
Syntax:
  #include <vector>
  iterator insert( iterator loc, const TYPE& val );
  void insert( iterator loc, size_type num, const TYPE& val );
  template<TYPE> void insert( iterator loc, input_iterator start, input_iterator end );

The insert() function either:

  • inserts val before loc, returning an iterator to the element inserted,
  • inserts num copies of val before loc, or
  • inserts the elements from start to end before loc.

Note that inserting elements into a vector can be relatively time-intensive, since the underlying data structure for a vector is an array. In order to insert data into an array, you might need to displace a lot of the elements of that array, and this can take linear time. If you are planning on doing a lot of insertions into your vector and you care about speed, you might be better off using a container that has a linked list as its underlying data structure (such as a List or a Deque).

For example, the following code uses the insert() function to splice four copies of the character 'C' into a vector of characters:

 // Create a vector, load it with the first 10 characters of the alphabet
 vector<char> alphaVector;
 for( int i=0; i < 10; i++ ) {
   alphaVector.push_back( i + 65 );
 }              

 // Insert four C's into the vector
 vector<char>::iterator theIterator = alphaVector.begin();
 alphaVector.insert( theIterator, 4, 'C' );             

 // Display the vector
 for( theIterator = alphaVector.begin(); theIterator != alphaVector.end(); theIterator++ )    {
   cout << *theIterator;
 }              

This code would display:

 CCCCABCDEFGHIJ         

Here is another example of the insert() function. In this code, insert() is used to append the contents of one vector onto the end of another:

  vector<int> v1;
  v1.push_back( 0 );
  v1.push_back( 1 );
  v1.push_back( 2 );
  v1.push_back( 3 );

  vector<int> v2;
  v2.push_back( 5 );
  v2.push_back( 6 );
  v2.push_back( 7 );
  v2.push_back( 8 );

  cout << "Before, v2 is: ";
  for( int i = 0; i < v2.size(); i++ ) {
    cout << v2[i] << " ";
  }
  cout << endl;

  v2.insert( v2.end(), v1.begin(), v1.end() );

  cout << "After, v2 is: ";
  for( int i = 0; i < v2.size(); i++ ) {
    cout << v2[i] << " ";
  }
  cout << endl;

When run, this code displays:

  Before, v2 is: 5 6 7 8
  After, v2 is: 5 6 7 8 0 1 2 3

Vector constructors
Syntax:
  #include <vector>
  vector();
  vector( const vector& c );
  vector( size_type num, const TYPE& val = TYPE() );
  vector( input_iterator start, input_iterator end );
  ~vector();

The default vector constructor takes no arguments, creates a new instance of that vector.

The second constructor is a default copy constructor that can be used to create a new vector that is a copy of the given vector c.

The third constructor creates a vector with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a vector consisting of five copies of the integer 42:

 vector<int> v1( 5, 42 );         

The last constructor creates a vector that is initialized to contain the elements between start and end. For example:

 // create a vector of random integers
 cout << "original vector: ";
 vector<int> v;
 for( int i = 0; i < 10; i++ ) {
   int num = (int) rand() % 10;
   cout << num << " ";
   v.push_back( num );
 }
 cout << endl;            

 // find the first element of v that is even
 vector<int>::iterator iter1 = v.begin();
 while( iter1 != v.end() && *iter1 % 2 != 0 ) {
   iter1++;
 }              

 // find the last element of v that is even
 vector<int>::iterator iter2 = v.end();
 do {
   iter2--;
 } while( iter2 != v.begin() && *iter2 % 2 != 0 );              

 cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;         

 cout << "new vector: ";
 vector<int> v2( iter1, iter2 );
 for( int i = 0; i < v2.size(); i++ ) {
   cout << v2[i] << " ";
 }
 cout << endl;            

When run, this code displays the following output:

 original vector: 1 9 7 9 2 7 2 1 9 8
 first even number: 2, last even number: 8
 new vector: 2 7 2 1 9          

All of these constructors run in linear time except the first, which runs in constant time.

The default destructor is called when the vector should be destroyed.


pop_back
Syntax:
  #include <vector>
  void pop_back();

The pop_back() function removes the last element of the vector.

pop_back() runs in constant time.


push_back
Syntax:
  #include <vector>
  void push_back( const TYPE& val );

The push_back() function appends val to the end of the vector.

For example, the following code puts 10 integers into a list:

   list<int> the_list;
   for( int i = 0; i < 10; i++ )
     the_list.push_back( i );           

When displayed, the resulting list would look like this:

 0 1 2 3 4 5 6 7 8 9            

push_back() runs in constant time.


rbegin
Syntax:
  #include <vector>
  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

The rbegin() function returns a reverse_iterator to the end of the current vector.

rbegin() runs in constant time.


rend
Syntax:
  #include <vector>
  reverse_iterator rend();
  const_reverse_iterator rend() const;

The function rend() returns a reverse_iterator to the beginning of the current vector.

rend() runs in constant time.


reserve
Syntax:
  #include <vector>
  void reserve( size_type size );

The reserve() function sets the capacity of the vector to at least size.

reserve() runs in linear time.


resize
Syntax:
  #include <vector>
  void resize( size_type num, const TYPE& val = TYPE() );

The function resize() changes the size of the vector to size. If val is specified then any newly-created elements will be initialized to have a value of val.

This function runs in linear time.


size
Syntax:
  #include <vector>
  size_type size() const;

The size() function returns the number of elements in the current vector.


swap
Syntax:
  #include <vector>
  void swap( const container& from );

The swap() function exchanges the elements of the current vector with those of from. This function operates in constant time.

For example, the following code uses the swap() function to exchange the values of two strings:

   string first( "This comes first" );
   string second( "And this is second" );
   first.swap( second );
   cout << first << endl;
   cout << second << endl;          

The above code displays:

   And this is second
   This comes first             

Vector operators
Syntax:
  #include <vector>
  TYPE& operator[]( size_type index );
  const TYPE& operator[]( size_type index ) const;
  vector operator=(const vector& c2);
  bool operator==(const vector& c1, const vector& c2);
  bool operator!=(const vector& c1, const vector& c2);
  bool operator<(const vector& c1, const vector& c2);
  bool operator>(const vector& c1, const vector& c2);
  bool operator<=(const vector& c1, const vector& c2);
  bool operator>=(const vector& c1, const vector& c2);

All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Individual elements of a vector can be examined with the [] operator.

Performing a comparison or assigning one vector to another takes linear time. The [] operator runs in constant time.

Two vectors are equal if:

  1. Their size is the same, and
  2. Each member in location i in one vector is equal to the the member in location i in the other vector.

Comparisons among vectors are done lexicographically.

For example, the following code uses the [] operator to access all of the elements of a vector:

 vector<int> v( 5, 1 );
 for( int i = 0; i < v.size(); i++ ) {
   cout << "Element " << i << " is " << v[i] << endl;
 }              

posted @ 2006-08-13 19:52 keyws 阅读(656) | 评论 (0)编辑 收藏

(一)

One of the basic classes implemented by the Standard Template Library is the vector class. A vector is, essentially, a resizeable array; the vector class allows random access via the [] operator, but adding an element anywhere but to the end of a vector causes some overhead as all of the elements are shuffled around to fit them correctly into memory. Fortunately, the memory requirements are equivalent to those of a normal array. The header file for the STL vector library is vector. (Note that when using C++, header files drop the .h; for C header files - e.g. stdlib.h - you should still include the .h.) Moreover, the vector class is part of the std namespace, so you must either prefix all references to the vector template with std:: or include "using namespace std;" at the top of your program.

Vectors are more powerful than arrays because the number of functions that are available for accessing and modifying vectors. Unfortunately, the [] operator still does not provide bounds checking. There is an alternative way of accessing the vector, using the function at, which does provide bounds checking at an additional cost. Let's take a look at several functions provided by the vector class:

1 unsigned int size(); // Returns the number of elements in a vector
2 push_back(type element); // Adds an element to the end of a vector
3 bool empty(); // Returns true if the vector is empty
4 void clear(); // Erases all elements of the vector
5 type at(int n); //Returns the element at index n, with bounds checking

also, there are several basic operators defined for the vector class:

=           Assignment replaces a vector's contents with the contents of another
==          An element by element comparison of two vectors
[]          Random access to an element of a vector (usage is similar to that
            of the operator with arrays.) Keep in mind that it does not provide
            bounds checking.

Let's take a look at an example program using the vector class:

				
 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     vector <int> example;         //Vector to store integers
 8     example.push_back(3);         //Add 3  onto the vector
 9     example.push_back(10);        //Add 10 to the end
10     example.push_back(33);        //Add 33 to the end

11     for(int x=0; x<example.size(); x++
12     {
13         cout<<example[x]<<" ";    //Should output: 3 10 33
14     }

15     if(!example.empty())          //Checks if empty
16         example.clear();          //Clears vector
17     vector <int> another_vector;  //Creates another vector to store integers
18     another_vector.push_back(10); //Adds to end of vector
19     example.push_back(10);        //Same
20     if(example==another_vector)   //To show testing equality
21     {
22         example.push_back(20); 
23     }
24     for(int y=0; y<example.size(); y++)
25     {
26         cout<<example[y]<<" ";    //Should output 10 20
27     }
28     return 0;
29 }
Summary of Vector Benefits

Vectors are somewhat easier to use than regular arrays. At the very least, they get around having to be resized constantly using new and delete. Furthermore, their immense flexibility - support for any datatype and support for automatic resizing when adding elements - and the other helpful included functions give them clear advantages to arrays.

Another argument for using vectors are that they help avoid memory leaks--you don't have to remember to free vectors, or worry about how to handle freeing a vector in the case of an exception. This simplifies program flow and helps you write tighter code. Finally, if you use the at() function to access the vector, you get bounds checking at the cost of a slight performance penalty.

(二)

 C++ vector is a container template available with Standard Template Library pack. This C++ vector can be used to store similar typed objects sequentially, which can be accessed at a later point of time. As this is a template, all types of data including user defined data types like struct and class can be stored in this container.

This article explains briefly about how to insert, delete, access the data with respect to the C++ vector. The type stl::string is used for the purposes of explaining the sample code. Using stl::string is only for sample purposes. Any other type can be used with the C++ vector.

The values can be added to the c++ vector at the end of the sequence. The function push_back should be used for this purpose. The <vector> header file should be included in all the header files in order to access the C++ vector and its functions.

 1 #include <vector>
 2 #include <string>
 3 #include <iostream.h>
 4 
 5 void main()
 6 {
 7     //Declaration for the string data
 8     std::string strData = "One";
 9     //Declaration for C++ vector
10     std:: vector <std::string> str_Vector;
11     str_Vector.push_back(strData);
12     strData = "Two";
13     str_Vector.push_back(strData);
14     strData = "Three";
15     str_Vector.push_back(strData);
16     strData = "Four";
17     str_Vector.push_back(strData);
18 }

The above code adds 4 strings of std::string type to the str_Vector. This uses std:: vector.push_back function. This function takes 1 parameter of the designated type and adds it to the end of the c++ vector.

Accessing Elements of C++ Vector:

   The elements after being added can be accessed in two ways. One way is our legacy way of accessing the data with vector.at(position_in_integer) function. The position of the data element is passed as the single parameter to access the data.

Using our normal logic for accessing elements stored in C++ Vector:

If we want to access all the data, we can use a for loop and display them as follows.

1 for(int i=0;i < str_Vector.size(); i++)
2 {
3     std::string strd = str_Vector.at(i);
4     cout<<strd.c_str()<<endl;
5 }

The std:: vector .size() function returns the number of elements stored in the vector.

Using C++ vector iterator provided by STL:

The next way is to use the iterator object provided by the STL. These iterators are general purpose pointers allowing c++ programmers to forget the intricacies of object types and access the data of any type.

1 std::vector<std::string>::iterator itVectorData;
2 for(itVectorData = str_Vector.begin();  itVectorData != str_Vector.end(); itVectorData++)
3 {
4     std::string strD = *(itVectorData);
5 }

Removing elements from C++ vector:

Removing elements one by one from specified positions in c++ vector is achieved with the erase function.

The following code demonstrates how to use the erase function to remove an element from position 2 in the str_Vector from our sample.

1 str_Vector.erase(str_Vector.begin() + 1 ,str_Vector.begin() + 2 );

 The following sample demonstrates how to use the erase() function for removing elements 2,3 in the str_Vector used in the above sample. 

1 str_Vector.erase(str_Vector.begin() + 1 ,str_Vector.begin() + 3 );

If one wants to remove all the elements at once from the c++ vector, the vector.clear() function can be used.

posted @ 2006-08-13 19:36 keyws 阅读(787) | 评论 (0)编辑 收藏

http://www.cprogramming.com/tutorial/stl/iterators.html

The concept of an iterator is fundamental to understanding the C++ Standard Template Library (STL) because iterators provide a means for accessing data stored in container classes such a vector, map, list, etc.

You can think of an iterator as pointing to an item that is part of a larger container of items. For intance, all containers support a function called begin, which will return an iterator pointing to the beginning of the container (the first element) and function, end, that returns an iterator corresponding to having reached the end of the container. In fact, you can access the element by "dereferencing" the iterator with a *, just as you would dereference a pointer.

To request an iterator appropriate for a particular STL templated class, you use the syntax

1 std::class_name<template_parameters>::iterator name

where name is the name of the iterator variable you wish to create and the class_name is the name of the STL container you are using, and the template_paramters are the parameters to the template used to declare objects that will work with this iterator. Note that because the STL classes are part of the std namespace, you will need to either prefix every container class type with "std::", as in the example, or include "using namespace std;" at the top of your program.

For instance, if you had an STL vector storing integers, you could create an iterator for it as follows:
1std::vector<int> myIntVector;
2std::vector<int>::iterator myIntVectorIterator;
Different operations and containers support different types of iterator behavior. In fact, there are several different classes of iterators, each with slightly different properties. First, iterators are distinguished by whether you can use them for reading or writing data in the container. Some types of iterators allow for both reading and writing behavior, though not necessarily at the same time.

Some of the most important are the forward, backward and the bidirectional iterators. Both of these iterators can be used as either input or output iterators, meaning you can use them for either writing or reading. The forward iterator only allows movement one way -- from the front of the container to the back. To move from one element to the next, the increment operator, ++, can be used.

For instance, if you want to access the elements of an STL vector, it's best to use an iterator instead of the traditional C-style code. The strategy is fairly straightforward: call the container's begin function to get an iterator, use ++ to step through the objects in the container, access each object with the * operator ("*iterator") similar to the way you would access an object by dereferencing a pointer, and stop iterating when the iterator equals the container's end iterator. You can compare iterators using != to check for inequality, == to check for equality. (This only works for one twhen the iterators are operating on the same container!)

The old approach (avoid)
 1 using namespace std;
 2 
 3 vector<int> myIntVector;
 4 
 5 // Add some elements to myIntVector
 6 myIntVector.push_back(1);
 7 myIntVector.push_back(4);
 8 myIntVector.push_back(8);
 9 
10 for(int y=0; y<myIntVector.size(); y++)
11 {
12     cout<<myIntVector[y]<<" ";  //Should output 1 4 8
13 }
The STL approach (use this)
 1 using namespace std;
 2 
 3 vector<int> myIntVector;
 4 vector<int>::iterator myIntVectorIterator;
 5 
 6 // Add some elements to myIntVector
 7 myIntVector.push_back(1);
 8 myIntVector.push_back(4);
 9 myIntVector.push_back(8);
10 
11 for(myIntVectorIterator = myIntVector.begin(); 
12         myIntVectorIterator != myIntVector.end();
13         myIntVectorIterator++)
14 {
15     cout<<*myIntVectorIterator<<" ";    //Should output 1 4 8
16 }
17 
As you might imagine, you can use the decrement operator, --, when working with a bidirectional iterator or a backward operator.

Iterators are often handy for specifying a particular range of things to operate on. For instance, the range item.begin(), item.end() is the entire container, but smaller slices can be used. This is particularly easy with one other, extremely general class of iterator, the random access iterator, which is functionally equivalent to a pointer in C or C++ in the sense that you can not only increment or decrement but also move an arbitrary distance in constant time (for instance, jump multiple elements down a vector).

For instance, the iterators associated with vectors are random access iterators so you could use arithmetic of the form
iterator + n
where n is an integer. The result will be the element corresponding to the nth item after the item pointed to be the current iterator. This can be a problem if you happen to exceed the bounds of your iterator by stepping forward (or backward) by too many elements.

The following code demonstrates both the use of random access iterators and exceeding the bounds of the array (don't run it!):
1 vector<int> myIntVector;
2 vector<int>::iterator myIntVectorIterator;
3 myIntVectorIterator = myIntVector.begin() + 2;
You can also use the standard arithmetic shortcuts for addition and subtraction, += and -=, with random access iterators. Moreover, with random access iterators you can use <, >, <=, and >= to compare iterator positions within the container.

Iterators are also useful for some functions that belong to container classes that require operating on a range of values. A simple but useful example is the erase function. The vector template supports this function, which takes a range as specified by two iterators -- every element in the range is erased. For instance, to erase an entire vector:
1 vector<int>::iterator myIntVectorIterator;
2 myIntVector.erase(myIntVectorIterator.begin(), myIntVectorIterator.end());
which would delete all elements in the vector. If you only wanted to delete the first two elements, you could use
1myIntVector.erase(myIntVectorIterator.begin(), myIntVectorIterator.begin()+2);
Note that various container class support different types of iterators -- the vector class, which has served as our model for iterators, supports a random access iterator, the most general kind. Another container, the list container (to be discussed later), only supports bidirectional iterators.

So why use iterators? First, they're a flexible way to access the data in containers that don't have obvious means of accessing all of the data (for instance, maps [to be discussed later]). They're also quite flexible -- if you change the underlying container, it's easy to change the associated iterator so long as you only use features associated with the iterator supported by both classes. Finally, the STL algorithms defined in <algorithm> (to be discussed later) use iterators.

Summary

The Good
  • The STL provides iterators as a convenient abstraction for accessing many different types of containers.
  • Iterators for templated classes are generated inside the class scope with the syntax
    class_name<parameters>::iterator
    
  • Iterators can be thought of as limited pointers (or, in the case of random access iterators, as nearly equivalent to pointers)
The Gotchas
  • Iterators do not provide bounds checking; it is possible to overstep the bounds of a container, resulting in segmentation faults
  • Different containers support different iterators, so it is not always possible to change the underlying container type without making changes to your code
  • Iterators can be invalidated if the underlying container (the container being iterated over) is changed significantly
posted @ 2006-08-13 19:04 keyws 阅读(525) | 评论 (0)编辑 收藏

2006年8月12日 #

       初学函数模版,一个“ bug” 让俺郁闷了一番,想了一个小时都没有想出所以然。虽求助于网络,发贴于 vckbase

       问题已经解决,帖子摘要如下:

      : 函数模版问题,为什么不能采用多文件方式。 
      : 郭晨 ( 书童)
所属论坛: C++ 论坛
本帖分数: 0
回复次数: 4
发表时间: 2006-8-12 19:09:50
正文内容:
1

#include <fstream>
#include <iostream>
using namespace std;
template<class Type >
Type min(Type a, Type b)
{
    return a < b ? a : b;
}

int main(int argc, char* argv[])
{
    cout << min(10, 20) << endl;
    return 0;
}

可以编译成功,运行得到正确结果。

2
)多文件方式

///////////////////////main.cxx
#include "min.h"
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
    cout << min(10, 20) << endl;
    return 0;
}
///////////////////////min.h
#ifndef _MIN_GHH_
#define _MIN_GHH_  1

template<class Type >
Type min(Type a, Type b);

#endif

//////////////////////min.cxx
#include "min.h"

template<class Type >
Type min(Type a, Type b)
{
    return a < b ? a : b;
}

编译报告错误:
Linking...
20060812_function_template.obj : error LNK2001: unresolved external symbol "int __cdecl min(int,int)" (?min@@YAHHH@Z)
Debug/20060812_function_template.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.

20060812_function_template.exe - 2 error(s), 0 warning(s)

////////////////////////////////////
问题:为什么会出现这种问题,如何解决?盼赐教。
最新修改:2006-8-12 19:41:10

 

回复人: newgun ( 书童

2006-8-12 19:34:29 ( 得分: 10

Re: 函数模版问题,为什么不能采用多文件方式。
c++标准中规定可以采用分离的编译模式,只需要通过在模板定义中的关键字template 之前加上关键字export 来声明一个可导出的函数模板当函数模板,被导出时我们就可以在任意程序文本文件中使用模板的实例如:
  // model2.h
//
分离模式: 只提供模板声明
template <typename Type> Type min( Type t1, Type t2 );
// model2.C
// the template definition
export template <typename Type>    //export
关键字
Type min( Type t1, Type t2 ) { /* ...*/ }

    
但是好像现在的好多编译器如vc7都还不支持这种结构,所以最好把模板的声明
和定义都放在头文件里

     

       感受:得到网友提示,真有一种“柳暗花明又一村”之感,这个所谓 bug 是这么简单又是这么不简单!

       一直认为应该是自己的错误,但没想到是编译器和标准兼容性的问题。看来自己的思维习惯应该有所改变了。应该多角度分析问题,而不能一味的想当然。

       Ps :自己也应该考虑尝试一个新的 C++ 编译器了,老用 vc ,感觉学的标准 C++ 都不纯,就象这次事件一样。

posted @ 2006-08-12 20:32 keyws 阅读(603) | 评论 (1)编辑 收藏

2006年8月11日 #

       屈指一数,两年小硕,已过算半。回忆研一,展望研二,心中颇多感慨,喜忧四七开。

       喜,相比入学之初,知识层虽无脱胎换骨之感,但也小有所学,比已比人,进步不少!

       忧,两年小硕,时间紧凑,于学术研究难有大成;再现实一点,虽学通信,但找一满意工作,仍压力不轻,任重道远!

       读研不似本科,成熟多了,也开始考虑现实,不敢虚浮度日,但真努力奋斗起来,仍有迷茫不知所为之惑。

       不过,还好,还有一颗虽笨拙但还善于反思的脑袋,虽弯路不少,但也算一步步的向前行了。

       两年,真的太短!何况已浪费一年光阴哉 ?!

       无论为了工作,为了毕业,还是为了自己做点成果来,都是该努力的时候了!

       不谈人生意义等等大道理,就是为了追求一种生存的基础,在一只脚已经踏入社会的时候,也该明白自己应该做些什么了!

       管理自己,做该做的事,做一个积极的自己!完善自我!努力! 

   

       Ps :谨以此文,做开博纪念,也为我意义上的研二开始的纪念。

 

posted @ 2006-08-11 22:28 keyws 阅读(668) | 评论 (0)编辑 收藏