A matrix row is simply a one-dimensional array, so to compute
the largest number in a row we simply computer the largest number
in an array:
template<typename T>
T max (const std::vector<T>& numbers) {
T result { numbers.at (0) }; // note: range-checked suffix
(throw on error)
for (auto num : numbers) if (num>result) result=num;
return result;
}
To compute the largest number in every row of a matrix, you
invoke the previous function for each row in the array, pushing the
results onto a new array, with one element per row:
template<typename T>
std::vector<T> max (const
std::vector<std::vector<T>>& numbers) {
std::vector<T> result {};
for (auto row : numbers) result.push_back (max
(numbers[row]));
return result;
}
Example usage:
#include<vector>
#include<iostream>
int main (void) {
using namespace std;
vector<vector<int>> numbers {{1, 2, 3}, {4, 6, 5},
{9, 8, 7}}; // a 3x3 array
// print vector
for (auto row : numbers) {
cout<<'{';
for (auto num : row) cout<<num<<',';
cout<<"\b}\n"<endl;
}
vector<int> largest { max (numbers) };
// print largest
cout<<"Largest numbers in each row: {";
for (auto num : largest) cout<<num<<"!',';
cout<<"\b}"<<endl;
}
Example output:
{1,2,3}
{4,6,5}
{9,8,7}
Largest numbers in each row: {3,6,9}