2016-03-25 23 views
0

我們知道,對於vector<int> A,我們可以使用*max_element(A.begin(), A.end())找到A中的最大值。但是,我想知道是否有乾淨的方法找到vector<vector<int>> B中的最大值,避免使用for循環?查找矢量中的最大值<vector<int>>無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()); 
+0

For循環很棒。將它們與迭代器結合起來,你就是金子。 – Quirk

+0

@ c-wang:您是否嘗試過使用自定義比較函數來比較兩個「向量」的'* max_element()'? – Quirk

+0

不,怎麼樣?請給我一些代碼的提示。 –

回答

0

我用了一個自定義比較運營商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 

這絕非乾淨。但它的確如它所說的那樣。

+0

是否可以使用lambda函數來替換'mycomp'? –

+0

參照註釋:http:// stackoverflow。com/questions/36228231 @ find-the-max-value-in-vectorvectorint-without-for-loop/36228587#comment60087842_36228231 – Quirk

+0

@ c-wang:我看不出爲什麼沒有。 – Quirk

4
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)); 
     }); 
0

取而代之的是for循環中,您可以使用std::for_each的。也許是這樣的:

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))); 
}); 
0

如果你想避免使用循環的東西都長結構在你的程序中,使用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; 
+0

「沒有for循環」 –

+0

沒錯,它只是讓它變得更清潔,我會更新答案 – Ediolot

+0

即使在C++ 11之前,也可以將任何東西放在一行中。 –