How to get greatest value of all integers in a 2d vector?

Viewed 86

I am trying to get maximum value my iterator is pointing at out of 2d array.

Example

Input

Data = {{}, {3,11,4}, {1,2}, {5,6}};

Output

max = 11

I have a 2d array and with max_element I tried to get the maximum out of the values in the array.

With a 1d iterator you can dereference the iterator and get the value i.e. *iteratorOneD. But how can I do something like this with a 2d iterator?

I tried a few things like this.

vector<vector <int>>::iterator position;
position = std::max_element(Data.begin(), Data.end());

int max = *position[0];

cout<< *position << endl;

But nothing worked yet. I receive this error.

C2440 "Initialisierung": "std::vector<int,std::allocator>" cant be converted to an int

The output of cout << *position << endl; is std::vector(1062256, 1027080). I would like to be able to assign one of these values to int max.

2 Answers

You could create an iterator "outside" std::max_element that keeps track of the greatest element so far.

int main() { 
    std::vector<std::vector<int>> Data{{}, {3,11,4}, {1,2}, {5,6}};

    // find the first non-empty vector
    auto ne = std::find_if(Data.begin(), Data.end(),
                           [](auto& v) { return !v.empty(); });

    if(ne == Data.end()) return 1; // no elements in **any** inner vector

    // set the inner iterator to the max element in the first non-empty vector
    auto inner = std::max_element(ne->begin(), ne->end());

    auto position = std::max_element(ne, Data.end(),
        [&inner](auto&, auto& v2) {
            if(v2.empty()) return false;

            // find the max_element in this inner vector
            auto tmp  = std::max_element(v2.begin(), v2.end());

            // is it greater than the one we had stored
            if(*inner < *tmp) {
                inner = tmp;
                return true;
            }
            return false;
        });

    std::cout << "the vector ";
    for(auto& col : *position) std::cout << col << ' ';
    std::cout << "contains the max element " << *inner << '\n';
}

Output:

the vector 3 11 4 contains the max element 11

From C++20, you can use range views to create a 1D view from your 2D vector

auto as1D = Data | std::views::join;

and then with range algorithms you can find the maximum element

int max = *std::ranges::max_element(as1D);

Here's a demo

Related