刚刚尝试初始化一个容器,刚好是空的,遇到如下现象:
#include <iostream>
#include <array>
#include <algorithm>
int main(int argc, char *argv[])
{
std::array<int,NULL> foo = {};
if ( std::all_of(foo.begin(), foo.end(), [](int i){return i==0;}) )
std::cout << "All the elements are zero.\n";
return 0;
}
编译:
clang++ -std=c++11 -stdlib=libc++ -o test test.cpp
结果:
bash-3.2$ ./test
All the elements are zero.
我想弄清楚为什么空容器会为此操作返回 true。此问题可能与以下内容有关: Behaviour of std::list:begin() when list is empty
但是我找不到这个特定问题的正确答案。
感谢您的宝贵时间。
最佳答案
如果范围为空,
std::all_of
返回 true
。来自25.2.1 全部
template <class InputIterator, class Predicate>
bool all_of(InputIterator first, InputIterator last, Predicate pred);
Returns:
true
if[first,last)
is empty or ifpred(*i)
istrue
for every iteratori
in the range[first,last)
, andfalse
otherwise.
关于C++ 空容器迭代器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25600484/