簡體   English   中英

如何在std :: vector上找到std :: max_element <std::pair<int, int> &gt;在哪一個軸?

[英]How to find std::max_element on std::vector<std::pair<int, int>> in either of the axis?

如何在這兩個軸中的std::vector<std::pair<int, int>>找到max元素。

讓它成為樣本對:

0, 1
0, 2
1, 1
1, 2
1, 4
2, 2
3, 1

我嘗試使用std::minmax_element()

const auto p = std::minmax_element(edges.begin(), edges.end());
auto max = p.second->first;

但這只生成第一列的最大元素,即3 ,但我想要列的最大元素,即4

我希望max元素是列中的最高元素。

std :: max_element與自定義比較函數一起使用,例如:

auto max_pair = *std::max_element(std::begin(edges), std::end(edges), 
    [](const auto& p1, const auto& p2) {
        return std::max(p1.first, p1.second) < std::max(p2.first, p2.second);
    });
int max = std::max(max_pair.first, max_pair.second);

您需要提供謂詞,該謂詞將為您的項目定義“更少”關系:

const auto p = std::minmax_element(
        edges.begin(), edges.end(),
        [](const auto& a, const auto& b) {
    // provide relation less you need, example:
    return std::max(a.first, a.second) < std::max(b.first, b.second);
});

默認情況下(在您的代碼中)使用較少的運算符。 對於std::pair它在元素的詞典排序中起作用(如果第一個元素較少則返回true,如果它們相等則檢查second元素,如果它們更少)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM