崔毅东 C++程序设计入门(下) 第10单元:月映千江未减明 – 模板 笔记

本文介绍了C++中的模板概念,包括函数模板和类模板的使用。通过实例展示了如何利用模板在编译期进行计算,如计算斐波那契数列,并探讨了模板元编程。此外,还讨论了一个涉及模板的编译错误,分析了无限递归的原因。
摘要由CSDN通过智能技术生成

第01节:初识模板

在这里插入图片描述在这里插入图片描述

第02节:函数模板

在这里插入图片描述

#include <iostream>
using namespace std;

template<class T>
T maxValue(T x, T y) {
  if (x > y)
    return x;
  else
    return y;
}

int main() {
  cout << "Maximum between 1 and 3 is " << 
          maxValue(1, 3) << endl;
  cout << "Maximum between 1.5 and 0.3 is " <<
          maxValue(1.5, 0.3) << endl;
  cout << "Maximum between 'A' and 'N' is " <<
          maxValue('A', 'N') << endl;
  cout << "Maximum between \"ABC\" and \"ABD\" is " <<
          maxValue("ABC", "ABD") << endl;
   return 0;
}

在这里插入图片描述在这里插入图片描述

#include <iostream>
using namespace std;

template<typename T, typename S>
T maxValue(T x, S y) {
  T x1 = static_cast<T>(y);  
  if (x > x1)
    return x;
  else
    return x1;
}

int main() {
  cout << "Maximum between 1.0 and 3 is " <<
          maxValue(1.0, 3) << endl;
  cout << "Maximum between 1 and 1.1 is " <<
          maxValue(1, 1.1) << endl;
  cout << "Maximum between 'A' and 90 is " <<
          maxValue('A', 90) << endl;

//  cout << "Maximum between 'A' and \"ABD\" is " <<
//          maxValue('A', "ABD") << endl;
   return 0;
}

字符串不能转换到字符 会编译报错
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
u10s02 - 使用模板在编译期计算斐波那契数列
模板是一种神奇的东西。涉及到模板的很多代码,都是编译器在编译阶段生成的。

除了代码生成之外,编译器在处理模板时,还会进行一些计算。

我们利用模板的这个特性,可以让编译器做一些数学运算。

比如,让编译器计算阶乘,而不是在程序运行时计算阶乘:参见维基百科的这篇文章:【模板元编程】

请你参考上面的文章,编写一个计算斐波那契数列的程序,贴到这里。

在数学上,费波那契数列是以递归的方法来定义:

F_0=0

F_1=1

F_n = F_{n-1}+ F_{n-2}(n≧2)

用文字来说,就是费波那契数列由0和1开始,之后的费波那契系数就由之前的两数相加。首几个费波那契系数是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233……

特别指出:0不是第一项,而是第零项。

答:

#include <iostream>
 
template < int N >
struct Fibonacci
{
    enum { value = Fibonacci < N - 1 >::value + Fibonacci < N - 2 >::value };
};
 
template <>
struct Fibonacci < 0 >
{
    enum { value = 0 };
};
 
template <>
struct Fibonacci < 1 >
{
    enum { value = 1 };
};
 
int main()
{
    std::cout << Fibonacci < 0 >::value << std::endl;
    std::cout << Fibonacci < 1 >::value << std::endl;
    std::cout << Fibonacci < 2 >::value << std::endl;
    std::cout << Fibonacci < 3 >::value << std::endl;
    std::cout << Fibonacci < 4 >::value << std::endl;
    std::cout << Fibonacci < 5 >::value << std::endl;
    std::cout << Fibonacci < 6 >::value << std::endl;
    std::cout << Fibonacci < 7 >::value << std::endl;
    std::cout << Fibonacci < 8 >::value << std::endl;
    std::cout << Fibonacci < 9 >::value << std::endl;
    std::cout << Fibonacci < 10 >::value << std::endl;
    std::cout << Fibonacci < 11 >::value << std::endl;
    std::cin.get();
    return 0;
}

(by 想飞的小笨猪)

第03节:实例:泛型排序

在这里插入图片描述

#include <iostream>
using namespace std;

void selectionSort(double [], int);
void printArray(double list[], int arraySize); // function prototype

int main()
{
  double list[] = {2, 1, -4, 4};
  selectionSort(list, 4);

  printArray(list, 4);
  return 0;
}

void printArray(double list[], int arraySize)
{
  for (int i = 0; i < arraySize; i++)
  {
    cout << list[i] <<  " ";
  }
}

void selectionSort(double list[], int arraySize)
{
  for (int i = arraySize - 1; i >= 1; i--)
  {
    // Find the maximum in the list[0..i]
    double currentMax = list[0];
    int currentMaxIndex = 0;

    for (int j = 1; j <= i; j++)
    {
      if (currentMax < list[j])
      {
        currentMax = list[j];
        currentMaxIndex = j;
      }
    }

    // Swap list[i] with list[currentMaxIndex] if necessary;
    if (currentMaxIndex != i)
    {
      list[currentMaxIndex] = list[i];
      list[i] = currentMax;
    }
  }
}

在这里插入图片描述
在这里插入图片描述

#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;

template<typename T>
void sort (T list[], int arraySize) 
{
  for (int i = arraySize - 1; i >= 1; i--) 
  {
    // Find the maximum in the list[0..i]
    T currentMax = list[0];
    int currentMaxIndex = 0;

    for (int j = 1; j <= i; j++) 
    {
      if (currentMax < list[j])
      {
        currentMax = list[j];
        currentMaxIndex = j;
      }
    }

    // Swap list[i] with list[currentMaxIndex] if necessary;
    if (currentMaxIndex != i)
    {
      list[currentMaxIndex] = list[i];
      list[i] = currentMax;
    }
  }
}

template<typename T>
void printArray(T list[], int arraySize)
{
  for (int i = 0; i < arraySize; i++)
  {
    cout << list[i] << " ";
  }
  cout << endl;
}

int main()
{
  int list1[] = {3, 5, 1, 0, 2, 8, 7};
  sort(list1, 7);
  printArray(list1, 7);

  double list2[] = {3.5, 0.5, 1.4, 0.4, 2.5, 1.8, 4.7};
  sort(list2, 7);
  printArray(list2, 7);

  string list3[] = {"Beijing", "Shanghai", "Guangzhou", "Shenzhen"};
  sort(list3, 4);
  printArray(list3, 4);
  return 0; 
}

在这里插入图片描述

第04节:类模板

在这里插入图片描述在这里插入图片描述
GenericStack.h

#ifndef STACK_H
#define STACK_H

template<typename T>
class Stack
{
public:
  Stack();
  bool empty();
  T peek();
  T push(T value);
  T pop();
  int getSize();

private:
  T elements[100];
  int size;
};

template<typename T>
Stack<T>::Stack()
{
  size = 0;
}

template<typename T>
bool Stack<T>::empty()
{
  return (size == 0);
}

template<typename T>
T Stack<T>::peek()
{
  return elements[size - 1];
}

template<typename T>
T Stack<T>::push(T value)
{
  return elements[size++] = value;
}

template<typename T>
T Stack<T>::pop()
{
  return elements[--size];
}

template<typename T>
int Stack<T>::getSize()
{
  return size;
}

#endif

TestGenericStack.cpp

#include <iostream>
#include <string>
#include "GenericStack.h"
using std::cout;
using std::endl;
using std::string;

int main()
{
  Stack<int> intStack;
  for (int i = 0; i < 10; i++)
    intStack.push(i);

  while (!intStack.empty())
    cout << intStack.pop() << " ";
  cout << endl;

  Stack<string> stringStack;
  stringStack.push("Beijing");
  stringStack.push("Shanghai");
  stringStack.push("Guangzhou");

  while (!stringStack.empty())
    cout << stringStack.pop() << " ";

  return 0;
}

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述
u10s04 - 调戏编译器:为啥编译器搞不定这段代码?
请你尝试编译如下这段代码,看看你的编译器报告什么错误信息? (如果有条件,请分别用C++2001标准、C++2011标准分别尝试编译一下)

你从编译器的错误信息中能够判断代码有什么语法错误吗?

#include
template
class InfRec {
public:
static const int value = InfRec< InfRec >::value;
};
int main() {
std::cout << InfRec::value << std::endl;
return 0;
}
答:InfRec< InfRec > 死递归了

by wohaaitinciu

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值