我需要一個while循環,它將邏輯條件應用於向量的每個元素。將條件應用於整個向量
例如,儘管(所有元素< 3)或同時(所有元素!= 3)
我能想到的唯一方法是寫而(矢量[1]!= 3 ||向量[2 ]!= 3 || ...)。如果我的矢量很大,那會很快增長。
在C++中有更好的方法嗎?
我需要一個while循環,它將邏輯條件應用於向量的每個元素。將條件應用於整個向量
例如,儘管(所有元素< 3)或同時(所有元素!= 3)
我能想到的唯一方法是寫而(矢量[1]!= 3 ||向量[2 ]!= 3 || ...)。如果我的矢量很大,那會很快增長。
在C++中有更好的方法嗎?
假設
std::vector<int> v;
if(std::all_of(v.cbegin(), v.cend(), [](int i){ return i < 3 }))
{
}
if(std::all_of(v.cbegin(), v.cend(), [](int i){ return i != 3 }))
{
}
預C++ 11
struct Check
{
int d;
Check(int n) : d(n) {}
bool operator()(int n) const
{ return n < d; }
};
// Copied from above link
template< class InputIt, class UnaryPredicate >
bool all_of(InputIt first, InputIt last, UnaryPredicate p)
{
for (; first != last; ++first) {
if (!p(*first)) {
return false;
}
}
return true ;
}
if(all_of(v.begin(), v.end(), Check(3)))
{
}
謝謝!我要去問C++ 11。 – holianoify 2014-10-02 06:21:09
不工作...似乎all_of只是C++ 11 – holianoify 2014-10-02 06:22:07
@holianoify&Galik不記得對不起,複製了模板實現 – P0W 2014-10-02 06:23:42
在C++ 11,答案基本上使用std::all
連同lambdas:
如果(標準::所有(v.begin(),v.end(),[](常量類型名稱的std ::衰變::類型&一個) {返回一個< 3; }) {7 *你的東西在這裏* /}
在C++ 03,你得鍛鍊的std ::所有和lambda表達式:
template<class Iter, Fn>
bool all(Iter i, Iter end, Fn fn)
{
for(;i!=end; ++i)
if(!fn(*i)) return false;
return true;
}
和<3
你需要像一個明確的類
class is_less_than_val
{
int val;
public:
is_less_than(int value) :val(value) {}
bool operator()(int var) const { return var<val; }
};
,這樣你可以寫
if(all(v.begin(),v.end(),is_less_than_val(3))
{ /* your stuff here */ }
如果你發現所有的functinal機械晦澀(C++ 03是沒這樣「簡單」,有沒有實質性型扣),並且喜歡多個程序的方法,
template<class Cont, class Val>
bool all_less_than(const Cont& c, const Val& v)
{
for(typename Cont::const_iterator i=c.cbegin(), i!=c.end(); ++i)
if(!(*i < v)) return false;
return true;
}
template<class Cont, class Val>
bool all_equal_to(const Cont& c, const Val& v)
{
for(typename Cont::const_iterator i=c.cbegin(), i!=c.end(); ++i)
if(!(*i == v)) return false;
return true;
}
在所有樣品中,無論代碼如何安排,一切都歸結爲一個循環,在搜索條件的否定時打破爲假。
當然,如果所有的數值比較,!(<)
是>=
和!(==)
爲!=
,但由於續和Val是模板參數,只用<和==結果是瓦爾實現的要求較少(可以是任何東西,不只是int
)
正如其他人所說,在C++ 11中,這個有 這個特殊函數。在預C++ 11,通常的習慣用法將涉及 std::find_if
,並與結束迭代對 結果的比較,例如:
struct Condition
{
// The condition here must be inversed, since we're looking for elements
// which don't meet it.
bool operator()(int value) const { return !(value < 3); }
};
// ...
while (std::find_if(v.begin(), v.end(), Condition()) == v.end()) {
// ...
}
這是這樣一個常見的成語,我繼續使用它在C++ 11 (儘管經常帶有lambda)。
如果您經常進行此項檢查,您可能需要查看一些替代方案,例如始終對矢量進行排序或跟蹤矢量的最大元素。這將檢查O(1)而不是O(N)。 – 2014-10-02 06:34:03