In the following code I have found the smallest number of each row of the matrix, but I need to subtract this number from the entire row
#include "iostream"
#include "conio.h"
using namespace std;
int main()
{
int mas[4][4] = {1, 3, 5, 6,
6, 4, 7, 4,
5, 5, 6, 2,
4, 0, 4, 1};
for (int i = 0; i < 4; i++) {
int min_row = mas[i][0];
for (int j = 0; j < 4; j++) {
if (mas[i][j] < min_row) {
min_row = mas[i][j];
}
}
cout << "Mínimo en la fila " << i+1 << ": " << min_row << endl;
}
_getch();
}
Thanks in advance.
You have to loop through the row one more time to subtract the value from each element:
Seeing as how you are using a two-dimensional array of dimensions known at compile time, I would take advantage of the following utilities from the
<algorithm>
C++ algorithm() library:std::min_element
: Finds the smallest element in the range [first, last).std::transform
: Applies the provided function to the provided range and stores the result in the other provided range.With these utilities you could have this code:
The range loop
for
goes through the array row by row, we look for the smallest element of the row withstd::min_element
which we pass the start and end of the row (begin(fila)
yend(fila)
) 1 , since this function returns an iterator we must dereference it to obtain the lesser value.Immediately afterwards we use the smallest value that we have just found in
std::transform
which we tell it that we want to transform the row from beginning to end (begin(fila)
andend(fila)
) and that said transformation will be saved in the same row (begin(fila)
); the transformation we apply is a lambda 2 that subtracts the smallest value from every received value.You can see the code working in Wandbox 三へ( へ՞ਊ ՞)へ ハッハッ.
1
std::begin
andstd::end
.2 Lambda Expression .