簡體   English   中英

在向量中找到最大值 <vector<int> &gt;沒有for循環

[英]Find the max value in vector<vector<int>> without for loop

我們知道對於vector<int> A ,我們可以使用*max_element(A.begin(), A.end())A找到最大值。 但是,我想知道是否有一種干凈的方法來找到vector<vector<int>> B的最大值,從而避免使用for循環?

如果我們使用for循環,則代碼可能很簡單:

int maxvalue = INT_MIN;
for (int i = 0; i < m; i++)
    for (int j = 0; j < n; j++)
        maxvalue = max(maxvalue, B[i][j]);

要么

int maxvalue = INT_MIN;
for (int i = 0; i < m; i++)
{
    int temp = *max_element(B[i].begin(), B[i].end());
    maxvalue = max(maxvalue, temp);
}

但是我仍然覺得它不夠干凈。 而且我不喜歡for循環。

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~最后,我選擇了以下代碼來實現:

auto itv = max_element(A.begin(), A.end(), [](vector<int>& a, vector<int>& b) 
        { return *max_element(a.begin(), a.end()) < *max_element(b.begin(), b.end()); });
int ans = *max_element(itv->begin(), itv->end());
auto max_value = std::accumulate(std::begin(B), std::end(B),
      std::numeric_limits<int>::min(), 
      [] (int cur_max, auto && vec) 
      { 
        return std::max(cur_max, *std::max_element(std::begin(v), std::end(v));
      });

可以使用std::for_each代替for循環。 也許像:

int maxvalue = std::numeric_limits<int>::min();
std::for_each(std::begin(B), std::end(B), [&maxvalue](const auto& v)
{
    maxvalue = std::max(maxvalue, *std::max_element(std::begin(v), std::end(b)));
});

如果要避免使用循環的東西是程序中的長結構,則使用c ++ 11可以在帶有循環的單行中找到最大值:

std::vector< std::vector<int> > w;


int max = 0;
for (auto i : w) for (auto j : i) max = j > max ? j : max;

要么

int max = 0;
for (auto i : w) for (auto j : i) if (j > max) max = j;

無論如何,我認為這不是一個好習慣。 此選項會更好:

int max = 0;
for (auto i : w) 
    for (auto j : i) 
        max = j > max ? j : max;

我在max_element()使用了自定義比較運算符,以獲得所需的效果。 除了max_element()隱含的累積運行外,沒有任何循環。

bool mycomp(vector<int> a, vector<int> b) {
  return *max_element(a.begin(), a.end()) < *max_element(b.begin(), b.end());
}

vector<vector<int>> vv; // our vector of vectors

auto itv = max_element(vv.begin(), vv.end(), mycomp); // find the vector 
                                                     // with the max element

int answer = *max_element((*itv).begin(), (*itv).end()); // finds the max element 
                                                        // in the desired vector

這絕對不是干凈的 但是它確實做到了它所說的。

暫無
暫無

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

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