给定二维矩阵,请使用多线程查找具有最大值的元素。
先决条件:多线程
例子 :
Input : {{1, 5, 3, 6},
{22, 10, 4, 34},
{4, 45, 67, 3},
{69, 3, 23, 3}}
Output :69
Input :{{1, 2, 3}
{2, 4, 5}}
Output :5
矩阵的尺寸可能非常大,因此遍历矩阵将花费大量时间。在矩阵中找到最大元素时,将遍历矩阵的每个元素,这将花费更多时间。因此,使用多线程可以避免将遍历矩阵所需的时间最小化。
// CPP code to find max in 2d
// array using multi-threading
#include
using namespace std;
// declaring two thread_id variable
pthread_t thread[2];
// structure for passing arguments
typedef struct dim
{
int s, e;
}dim;
// matrix of 4X4
int mat1[][4] = {{1, 5, 3, 6}, {22, 80, 4, 34},
{4, 45, 67, 3}, {99, 3, 23, 3}};
int maxf[2];
// function that find max from a given array
void *max(void *size)
{
int i, j, max;
dim *b = (dim *)size;
max = mat1[b -> s][0];
// finding max
for(i = b -> s; i < b -> e; i++)
{
for(j = 0; j < 4; j++)
{
if(max < mat1[i][j])
max = mat1[i][j];
}
}
// storing max from first half of
// 2-d array into 0th index
if(b -> s == 0)
maxf[0] = max;
// storing max from second half of
// 2-d array into 1st index
else
maxf[1] = max;
}
// driver function
int main()
{
int i, j;
dim *a, *b;
a = (dim *)malloc(sizeof(dim));
b = (dim *)malloc(sizeof(dim));
// creating thread1
a -> s = 0; a -> e = 4/2;
pthread_create(&thread[0], NULL,
&max, (void *)a);
b -> s = 4/2; b -> e = 4;
// creating thr ead 2
pthread_create(&thread[1], NULL,
&max, (void *)b);
// waiting until the complition of threads
pthread_join(thread[0], NULL);
pthread_join(thread[1], NULL);
// printing max
if(maxf[0] > maxf[1])
cout << maxf[0] << endl;
else
cout<< maxf[1] << endl;
return 0;
}
输出 :
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。