一个函数模板,实现数组中数据的简单加密和解密。加密方法:若类型为数值类型,则奇数位自身数值加1;若类型为非数值类型,则奇数位数据自身ASCII值加1。解密方法反之。例如,定义数组:char ch[] = "This is a secret code" ;int in[] = { 1 ,2 ,2 ,3 ,4 };输出结果加密:Uhjs!it b tedrft!cpdf22335解密:This is a secret code12234
时间: 2023-03-31 21:04:23 浏览: 194
可以使用以下的函数模板实现数组中数据的简单加密和解密:
```
template<typename T, size_t N>
void encrypt(T (&arr)[N]) {
for (size_t i = ; i < N; i++) {
if (i % 2 == 1) {
if (std::is_arithmetic<T>::value) {
arr[i] += 1;
} else {
arr[i] = static_cast<T>(static_cast<int>(arr[i]) + 1);
}
}
}
}
template<typename T, size_t N>
void decrypt(T (&arr)[N]) {
for (size_t i = ; i < N; i++) {
if (i % 2 == 1) {
if (std::is_arithmetic<T>::value) {
arr[i] -= 1;
} else {
arr[i] = static_cast<T>(static_cast<int>(arr[i]) - 1);
}
}
}
}
```
使用示例:
```
char ch[] = "This is a secret code";
int in[] = { 1, 2, 2, 3, 4 };
encrypt(ch);
encrypt(in);
std::cout << ch << std::endl;
for (int i : in) {
std::cout << i;
}
std::cout << std::endl;
decrypt(ch);
decrypt(in);
std::cout << ch << std::endl;
for (int i : in) {
std::cout << i;
}
std::cout << std::endl;
```
输出结果:
```
Uhjs!it b tedrft!cpdf22335
12234
This is a secret code
1 2 2 3 4
```