题目说明:
示例代码:
// Day21_Generics.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
template <class T> void printArray( vector<T> a )
{
for( T i : a )
{
cout << i << endl;
}
}
//by zhaocl
int main()
{
int n;
cin >> n;
//int
vector<int> int_vector( n );
for( size_t i = 0; i < n; i++ )
{
int value;
cin >> value;
int_vector[i] = value;
}
//string
cin >> n;
vector<string> string_vector( n );
for( size_t i = 0; i < n; i++ )
{
string value;
cin >> value;
string_vector[i] = value;
}
printArray<int>( int_vector );
printArray<string>( string_vector );
system( "pause" );
return 0;
}
知识点:
1、c++类模板的使用
2、泛型的使用:虽然使用函数重载也可以实现功能,但是不符合代码的重用