【1】题目
【2】思路
【3】程序源码
// test2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<fstream>
#include<vector>
using namespace std;
//寻找二维数组中的一个元素
bool selectnum(vector<vector<int>> matrix, int num)
{
bool flag = false;
if (matrix.empty()) { return flag; }
int rows = matrix.size();
int cols= matrix[0].size();
if (rows >= 0 && cols >=0){
int row = 0;
int col = cols-1;
while (row<rows && col>=0){
if (matrix[row][col]==num){
flag = true;
cout << "position:" << row << "," << col << endl;
break;
}
else if (matrix[row][col] < num){
row++;
}
else{
col--;
}
}
}
return flag;
}
void main()
{
vector<vector<int>> matrix;
vector<int> a = { 1,2,3,4 };
vector<int> b = { 11,12,13,14 };
vector<int> c = { 21,22,23,24 };
vector<int> d = { 31,32,33,34 };
matrix.push_back(a);
matrix.push_back(b);
matrix.push_back(c);
matrix.push_back(d);
bool flag = selectnum(matrix, 12);
cout << flag << endl;
cin.get();
}