c 模板怎么用

模板是简单但非常强大的C ++工具。简单的想法是将数据类型作为参数传递,这样我们就不需要为不同的数据类型编写相同的代码。例如,软件公司可能需要sort()用于不同的数据类型。我们可以编写一个sort()并将数据类型作为参数传递,而不是编写和维护多个代码。

C ++添加了两个新的关键字来支持模板:'template'和'typename'。第二个关键字始终可以替换为关键字“class”。

模板如何工作?

模板在编译时扩展。这就像宏。不同的是,编译器在模板扩展之前进行类型检查。这个想法很简单,源代码只包含函数/类,但编译后的代码可能包含相同函数/类的多个副本。

c 模板怎么用

功能模板我们编写了一个可用于不同数据类型的通用函数。函数模板的示例有sort(),max(),min(),printArray()

#include <iostream>

using namespace std;

// One function works for all data types. This would work

// even for user defined types if operator '>' is overloaded

template <typename T>

T myMax(T x, T y)

{

return (x > y)? x: y;

}

int main()

{

cout << myMax<int>(3, 7) << endl; // Call myMax for intaTRwUxDA

cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double

cout << myMax<char>('g', 'e') << endl; // call myMax for char

return 0;

}

输出:

7

7

G

下面是使用CaTRwUxDA ++中的模板实现冒泡排序的程序:

// CPP code for bubble sort

// using template function

#include <iostream>

using namespace std;

// A template function to implement bubble sort.

// We can use this for any data type that supports

// comparison operator < and swap works for it.

template <class T>

void bubbleSort(T a[], int n) {

for (int i = 0; i < n -www.58yuanyou.com 1; i++)

for (int原由网 j = n - 1; i < j; j--)

if (a[j] < a[j - 1])

swap(a[j], a[j - 1]);

}

// Driver Code

int main() {

int a[5] = {10, 50, 30, 40, 20};

int n = sizeof(a) / sizeof(a[0]);

// calls template function

bubbleSort(a, 5);

cout << " Sorted array : ";

for (int i = 0; i < n; iwww.58yuanyou.com++)

cout << a[i] << " ";

cout << endl;

return 0;

}

输出

分类阵列:10 20 30 40 50

类模板与函数模板一样,当类定义与数据类型无关的内容时,类模板很有用。可用于LinkedList,BinaryTre,Stack,Queue,Array等类。

以下是模板Array类的简单示例。

#include <iostream>

using namespace std;

template <typename T>

class Array {

private:

T *ptr;

int size;

public:

Array(T arr[], int s);

void print();

};

template <typename T>

Array<T>::Array(T arr[], int s) {

ptr = new T[s];

size = s;

for(int i = 0; i < size; i++)

ptr[i] = arr[i];

}

template <typename T>

void Array<T>::print() {

for (int i = 0; i < size; i++)

cout<<" "<<*(ptr + i);

cout<<endl;

}

int main() {

int arr[5] = {1, 2, 3, 4, 5};

Array<int> a(arr, 5);

a.print();

return 0;

}

输出:

1 2 3 4 5

内容版权声明:除非注明原创否则皆为转载,再次转载请注明出处。

文章标题: c 模板怎么用

文章地址: www.58yuanyou.com/jiqiao/148735.html

相关推荐