c++ - 如何获得二维 vector 中所有整数的最大值?

标签 c++ iterator 2d

我正在尝试获取迭代器指向的二维数组的最大值。

示例

输入

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

输出

max = 11

我有一个二维数组和 max_element我试图从数组中的值中获取最大值。

使用 1d 迭代器,您可以取消引用迭代器并获取值,即 *iteratorOneD 。但是我怎样才能用 2d 迭代器做这样的事情呢?

我尝试了一些类似的事情。

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

int max = *position[0];

cout<< *position << endl;

但是还没有任何效果。我收到此错误。

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

cout << *position << endl; 的输出是 std::vector(1062256, 1027080) 。 我希望能够将这些值之一分配给 int max .

最佳答案

您可以在std::max_element“外部”创建一个迭代器来跟踪迄今为止最大的元素。

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';
}

输出:

the vector 3 11 4 contains the max element 11

关于c++ - 如何获得二维 vector 中所有整数的最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67382114/

相关文章:

c++ - 带字段的静态方法

c++ - 如何遍历 QMultiHash 中的所有 values()

android - Android 中 SurfaceView Canvas 上位图的碰撞检测

c++ - 需要有关二维数组的建议

java - 如何将数据存储在二维数组列表中并使用双迭代器显示它们?

c - C 中的二维傅里叶变换

c++ - 带有 OpenGL (freeglut) 的 SDL 在调用 glutBitmapCharacter 时崩溃

c++ - 漂亮地打印 C++ 中的变量和值列表

c++ 项目构建成功但给出 g++ 编译器错误消息

c++ - 使用 std::copy 时 istream_iterator 无效