题目:
C++:
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <math.h>
#include <stdexcept>
#include <exception>
#include <iostream>
using namespace std;
/**
* Name: printArray
* Print each element of the generic vector on a new line. Do not return anything.
* @param A generic vector
**/
// Write your code here
template <typename T>
void printArray(vector<T> valList)
{
//for (auto val : valList)//C++11新增的对vector的迭代输出
//{
// cout << val << endl;
//}
int count = valList.size();
for (int i = 0; i < count; i++)
{
cout << valList[i] << endl;
}
}
int main() {
int n;
cin >> n;
vector<int> int_vector(n);
for (int i = 0; i < n; i++) {
int value;
cin >> value;
int_vector[i] = value;
}
cin >> n;
vector<string> string_vector(n);
for (int 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;
}
参考:https://blog.csdn.net/myruo/article/details/79692263
总结:
C++:
vector的定义:
int n;
cin >> n;
vector<int> int_vector(n);
for (int i = 0; i < n; i++) {
int value;
cin >> value;
int_vector[i] = value;
}
vector的遍历输出:
方式一:
for (auto val : valList)//C++11新增的对vector的迭代输出
{
cout << val << endl;
}
方式二:
int count = valList.size();
for (int i = 0; i < count; i++)
{
cout << valList[i] << endl;
}
泛型,函数模板
template <typename T> //声明使用模板,并定义T是一个模板类型
void Swap(T& a, T& b) //紧接着使用T
{
T c = a;
a = b;
b = c;
}
参考:https://www.cnblogs.com/xylc/p/3653036.html
https://www.cnblogs.com/cxq0017/p/6076856.html