Home > Enterprise >  C Finding max value in a vector of vectors
C Finding max value in a vector of vectors

Time:12-11

I'm still pretty rusty with C , so would like to know if there is a more concise way of finding the maximum value in a vector of vectors. Here's what I have come up with:

std::vector<std::vector<int>> score;

This score variable is populated by some other code. I want the max value stored:

int max_value()
{
    std::vector<int> row_maximums;

    for (auto row = score.begin(); row != score.end();   row)
    {
        row_maximums.push_back(*std::max_element(row->begin(), row->end()));
    }
    return *std::max_element(row_maximums.begin(), row_maximums.end());
}

I'm largely a C# dev so would normally be used to doing it on one line with LINQ:

List<List<int>> score;

public int max_value => score.Aggregate(0, (current, row) => row.Prepend(current).Max());

Thanks for any tips!

CodePudding user response:

Assuming you can use C 20, I would simply write:

auto max_value = std::ranges::max(score | std::views::join);

join flattens the vector from 2d to 1d, and max gives you the max value of the range

Working example: godbolt.org

CodePudding user response:

int max_value()
{
    int ret = std::numeric_limits<int>::min();
    for (auto& row : score)
    {
        for (auto& j : row) {
            if (j > ret)
                ret = j;
        }
    }
    return ret;
}

Just want to show that things maybe much simpler than you thought :D

the for (auto& row : score) {...} is equivalent to for (auto it = score.begin(); it != score.end(); it) { auto& row = *it; ... }, but shorter in this scenario. (only available since C 11 of course)

  •  Tags:  
  • c
  • Related