一千萬個為什麽

搜索

如何從lambda中的函數返回?

考慮以下玩具代碼以確定範圍是否包含元素:

template
bool contains1(Iter begin, Iter end, const T& x)
{
    for (; begin != end; ++begin)
    {
        if (*begin == x) return true;
    }
    return false;
}

(是的,我知道,標準庫中已有完美的算法,但這不是重點。)

我如何用 for_each 和lambda編寫相同的東西?以下不起作用......

template
bool contains2(Iter begin, Iter end, const T& x)
{
    std::for_each(begin, end, [&x](const T& y) {
        if (x == y) return true;
    });
    return false;
}

...因為那只會從lambda返回,而不是從函數返回。

我是否必須拋出異常以擺脫lambda?同樣,對於這個特定問題可能有十幾個更好的解決方案,根本不涉及lambda,但這不是我要求的。

最佳答案

std::for_each is not the algorithm you should use if you want to end the loop early. It seems you want std::find_if or something similar. You should use the algorithm that is most appropriate to your task, not just the one you're familiar with.


如果你真的,真的真的必須盡早從算法“返回”,你可以 -

Warning: what follows is a really, really bad idea and you should virtually never do it. Indeed, looking at the code may melt your face. You have been warned!

拋出異常:

bool contains2(Iter begin, Iter end, const T& x)
{
  try {
    std::for_each(begin, end, [&x](const T& y) {
        if (x == y)
          throw std::runtime_error("something");
    });
  }
  catch(std::runtime_error &e) {
    return true;
  }
  return false;
}

轉載註明原文: 如何從lambda中的函數返回?