关于c++:模板函数中以引用的方式传递数组

2次阅读

共计 927 个字符,预计需要花费 3 分钟才能阅读完成。

本文基于《数据结构、算法与利用 C ++ 语言形容》一书。

其中,在第一章的练习 2 中,有一个题目是这样形容的:

编写一个模板函数 count,返回值是数组 a[0:n-1] 中 value 呈现的次数。测试你的代码。

书中给出的代码是这样的:

template<class T>
T count(T a[], int n, const T& value)
{
    int theCount = 0;
    for(int i = 0; i < n; i++)
        if(a[i] == value)
            theCount++;
    return theCount;
}

然而出于好奇想要尝试一下以援用的形式去传递这个数组,于是有

template<class T, int n>
T count(T (&a)[n], const T& value)
{
    int i, t;

    t = 0; // t -> time
    for(i = 0; i < n; i++)
        if(a[i] == value)
            ++t;
    return t;
}

残缺代码

#include <iostream>
#include <iterator>

using namespace std;

template<class T, int n>
T count(T (&a)[n], const T& value)
{
    int i, t;

    t = 0; // t -> time
    for(i = 0; i < n; i++)
        if(a[i] == value)
            ++t;
    return t;
}

int main()
{int a[6] = {1, 2, 3, 4, 1, 1};

    cout << "a[0:5] =";
    copy(a, a+6, ostream_iterator<int>(cout, " "));
    cout << "\n";

    cout << "count(a, 1) =" << count(a, 1) << "\n";
    cout << "count(a, 2) =" << count(a, 2) << "\n";

    system("pause");
    return 0;
}

后果

a[0:5] = 1 2 3 4 1 1
count(a, 1) = 3
count(a, 2) = 1

参考列表

  1. How to write a template function that takes an array and an int specifying array size
  2. Data Structures, Algorithms, & Applications in C++ Chapter 1, Exercise 2
正文完
 0