C++实现在多维数组中的查找
作者:野牛程序员:2023-12-14 16:51:19 C++阅读 2794
多维数组中的查找可以通过嵌套循环来实现。以下是一个示例的C++代码,用于在一个二维数组中查找特定的元素:
#include <iostream>
bool searchIn2DArray(int target, int array[][3], int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (array[i][j] == target) {
return true;
}
}
}
return false;
}
int main() {
int rows = 3;
int cols = 3;
int myArray[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int target = 5;
bool found = searchIn2DArray(target, myArray, rows, cols);
if (found) {
std::cout << "元素 " << target << " 存在于数组中。" << std::endl;
} else {
std::cout << "元素 " << target << " 不存在于数组中。" << std::endl;
}
return 0;
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C语言中怎么实现求三科成绩平均分并输出最高分
- 下一篇:c语言获取数组元素个数
