是否有 STL/boost 算法来检查容器中的所有元素是否与某个值匹配?
是否有 STL/boost 算法可以测试两个迭代器之间的所有元素是否与给定值匹配?或者谓词对所有这些都返回 true
?
即类似
template<class InputIterator, class T>
InputIterator all_match (InputIterator first, InputIterator last, const T& value)
{
bool allMatch = true;
while(allMatch && first!=last)
allMatch = (value == *first++);
return allMatch;
}
或
template <class InputIterator, class Predicate>
bool all_true (InputIterator first, InputIterator last, Predicate pred)
{
bool allTrue = true;
while (allTrue && first != last)
allTrue = pred(*first++);
return allTrue;
}
Is there an STL/boost algorithm that will test if all the elements between two iterators match a given value? Or alternatively that a predicate returns true
for all of them?
i.e. something like
template<class InputIterator, class T>
InputIterator all_match (InputIterator first, InputIterator last, const T& value)
{
bool allMatch = true;
while(allMatch && first!=last)
allMatch = (value == *first++);
return allMatch;
}
Or
template <class InputIterator, class Predicate>
bool all_true (InputIterator first, InputIterator last, Predicate pred)
{
bool allTrue = true;
while (allTrue && first != last)
allTrue = pred(*first++);
return allTrue;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您可以否定谓词,则可以使用 std::find / std::find_if 并查看它是否返回序列的结束元素。如果不匹配,则返回匹配的那个。
您可以使用 std::not1 或 std::not_equal_to 来调整函数,因此通过与 std::find_if 结合使用您确实可以使用 STL 来做到这一点,而无需编写循环。
If you can negate the predicate you can use std::find / std::find_if and see if it returns the end element of your sequence. If not then it returns the one that does match.
You can adapt an function with std::not1 or std::not_equal_to so by doing combined with std::find_if you can indeed do so using STL without writing a loop.
C++11 引入了
std::all_of
。C++11 introduces
std::all_of
.您可以使用 std:find 或 std::find_if 来执行此操作。
You could use std:find ord std::find_if to do this.
您可以将
std::equal
与谓词一起使用。像这样的东西:You can use
std::equal
with the predicate. Something like:通常你可以只计算它们:
当迭代器不是随机的或者当它返回 false 时,效率很低。不适用于输入迭代器。
Often you can just count them:
Inefficient when the iterator isn't random, or when it returns false. Doesn't work for input iterators.