Reputation: 299
I know how to get the max value of the row of a 2D std::vector as follows:
std::vector<std::vector<int>> a = {{ 1, 45, 54}, {71, 76, 12 }, {74451, 756, 125 }};}
std::cout << " The max value of row 0 is: " << *max_element(begin(a[0]), end(a[0]));
How do you do call max_element to get the max value of a 2D vector column instead? (without copying the column into a 1D vector)
Thanks!
Upvotes: 1
Views: 1397
Reputation: 23792
As an alternative to std::max_element
you can use a vector of vectors iterator to iterate over any column and find the max value, something like:
int maxValue(const std::vector<std::vector<int>> &a, size_t col)
{
int max_value = 0; //assuming non negative values in the vector
try
{
for (auto it = a.begin(); it != a.end(); it++)
max_value = it->at(col) > max_value ? it->at(col) : max_value;
}
catch (std::out_of_range &e)
{
return -1; // or whatever you'd like
}
return max_value;
}
int main()
{
std::vector<std::vector<int>> a = {{1, 45, 54}, {71, 76, 12}, {74451, 756, 125}};
std::cout << maxValue(a, 0) << " "; // first column
std::cout << maxValue(a, 1) << " "; // second column
std::cout << maxValue(a, 2) << " "; // third column
std::cout << maxValue(a, 3); // out of range
}
Output:
74451 756 125 -1
Upvotes: 1
Reputation: 48605
What you can do is provide std::max_element
with a user-defined comparator that compares each std::vector<int>
in a
by the values in the desired column to search.
Like this:
std::vector<std::vector<int>> a = {{ 1, 45, 54}, {71, 76, 12 }, {74451, 756, 125 }};
std::cout << " The max value of row 0 is: " << *max_element(begin(a[0]), end(a[0])) << '\n';
auto max_col_0 = (*std::max_element(begin(a), end(a), [](auto& a, auto& b){ return a[0] < b[0]; }))[0];
auto max_col_1 = (*std::max_element(begin(a), end(a), [](auto& a, auto& b){ return a[1] < b[1]; }))[1];
std::cout << " The max value of col 0 is: " << max_col_0 << '\n';
std::cout << " The max value of col 1 is: " << max_col_1 << '\n';
Here the llambda function is called with two std::vector<int>
objects to compare and you need to compare the values in the given column you are searching. Resolving the auto
types will give this for the comparator:
[](std::vector<int>& a, std::vector<int>& b){ return a[1] < b[1]; }
The std::max_element
function calls the comparator with each of vector a
's stored vectors so that the relevant column in each vector can be compared for which is the lesser.
The returned iterator is to the winning std::vector<int>
from which you need to extract the winning column after dereferencing the iterator.
Upvotes: 2
Reputation: 1155
Let's say the column for which you need to find the max value is c
. You can then just iterate through that column.
int m = a[0][c]; // initialize the maximum to be value of column c in first row.
for(int i = 1; i < a.size(); i++){ // loop through all rows.
m = max(m, a[i][c]);
}
cout<<"Maximum value in column "<<c<<" is "<<m<<endl;
Upvotes: 2