Day 21: Generics

题目:

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

           https://www.cnblogs.com/lifexy/p/8761325.html

           https://www.cnblogs.com/study-development/p/4215687.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值