使用remove_if
或remove_copy_if
,not1
(在<functional>
中定義)來反轉謂詞。就像這樣:
#include <algorithm>
#include <functional>
template <class ForwardIterator, class Predicate>
ForwardIterator filter(ForwardIterator first, ForwardIterator last,
Predicate pred)
{
return std::remove_if(first, last, std::not1(pred));
}
template <class InputIterator, class OutputIterator, class Predicate>
OutputIterator filter_copy(InputIterator first, InputIterator last,
OutputIterator result, Predicate pred)
{
return std::remove_copy_if(first, last, result, std::not1(pred));
}
'std :: remove_copy_if()'與你想要的相反嗎?相反的是什麼? (container.begin(),container.end(),pred()),container.end()。如果你只想刪除元素,使用remove/erase idiom:container.erase(std :: remove_if );' – wilx 2010-09-03 12:49:34
@wilx:我想要保留滿足謂詞的元素,並刪除其他元素。 – missingfaktor 2010-09-03 12:51:18