c++ 数组判断是否有某个值
可以使用循环遍历数组,然后逐个比较元素和目标值是否相等来判断数组中是否存在某个值。以下是一个示例代码:
#include <iostream>
bool containsValue(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return true;
}
}
return false;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3;
if (containsValue(arr, size, target)) {
std::cout << "数组中存在目标值" << std::endl;
} else {
std::cout << "数组中不存在目标值" << std::endl;
}
return 0;
}
在上述示例中,containsValue函数接受一个整型数组、数组大小和目标值作为参数。它使用循环遍历数组,如果找到与目标值相等的元素,则返回true,否则返回false。在main函数中,我们定义了一个整型数组arr,然后通过sizeof操作符计算数组的大小,并将目标值设为3。最后,我们调用containsValue函数判断数组中是否存在目标值,并输出相应的结果。
原文地址: https://www.cveoy.top/t/topic/i5VZ 著作权归作者所有。请勿转载和采集!