C++ 泛型函数判断数组是否包含某个值
可以使用模板来定义一个泛型函数来判断数组是否包含某个值。以下是一个示例代码:
#include <iostream>
template <typename T, size_t N>
bool containsValue(const T (&arr)[N], const T& value) {
for (size_t i = 0; i < N; i++) {
if (arr[i] == value) {
return true;
}
}
return false;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
if (containsValue(arr, 3)) {
std::cout << 'Array contains the value 3' << std::endl;
} else {
std::cout << 'Array does not contain the value 3' << std::endl;
}
if (containsValue(arr, 6)) {
std::cout << 'Array contains the value 6' << std::endl;
} else {
std::cout << 'Array does not contain the value 6' << std::endl;
}
return 0;
}
在上面的代码中,containsValue 函数使用了模板来接受任意类型的数组和值。它使用了引用形参来传递数组和值,以避免数组的复制。函数内部使用循环遍历数组,如果找到与给定值相等的元素,则返回 true;如果遍历完整个数组仍未找到相等的元素,则返回 false。
原文地址: https://www.cveoy.top/t/topic/mBsq 著作权归作者所有。请勿转载和采集!