A. 【普及】如何封装我的算法

    传统题 100ms 64MiB

【普及】如何封装我的算法

【普及】如何封装我的算法

0、什么是封装算法

  • 简而言之,就是将某个算法的代码写规划,并且在下次要用到的时候,可以直接复制粘贴,拿来就用
  • 问:老师,我很强,我可以每次都重写一遍
  • 答:那是因为你现在接触的算法都太短

1、template 的应用

比如我想实现两个 int 相加的函数 addInt()

int addInt(int a, int b) {
    return a + b;
}

同时我还想实现两个 double 相加的函数 addDouble()

double addDouble(double a, double b) {
    return a + b;
}

当然我还想实现两个 string 相加的函数 addString()

string addString(string a, string b) {
    return a + b;
}
  • 那我是不是要写 3 个函数呢?
  • 不,你可以这样
  • template<typename T>:表示我的函数 add() 里面有一个类型 T,只有在 add() 被调用的时候才知道
  • 注意:这里用 typenameclass 都可以
#include <bits/stdc++.h>
using namespace std;

// 也可以写:template<class T>
template<typename T>
T add(T a, T b) {
	return a + b;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	
	cout << add(1, 2) << '\n';      // 3
	cout << add(1.1, 2.2) << '\n';  // 3.3
	
	string x = "11", y = "22";
	cout << add(x, y) << '\n';      // 1122
	
//	cout << add(1, 1.2) << '\n';    // 编译错
	return 0;
}

2、struct + template 的王炸组合

大家知道 vector 是怎么实现切换类型的嘛?

vector<int> a = {1, 2, 3};
vector<double> b = {1.1, 2.2, 3.3};
vector<string> c = {"ab", "cd", "ef"};

假设现在有一个结构体

struct Node {
    int a;
};

我想让 Node 里面的变量 a,也实现多种类型切换,怎么做呢?

#include <bits/stdc++.h>
using namespace std;

template<typename T>
struct Node {
	T a;
};

int main() {
	Node<int> x;
	x.a = 1;
	
	Node<string> y;
	y.a = "abc";
	return 0;
}

大家现在知道:vector 是怎么实现切换类型的了吧

请你用 template 实现一个 add() 函数,即可通过本题目