我只是试图初始化一个容器,它碰巧是空的,并且遇到了以下现象:
#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;
}
Run Code Online (Sandbox Code Playgroud)
编译:
clang++ -std=c++11 -stdlib=libc++ -o test test.cpp
Run Code Online (Sandbox Code Playgroud)
导致:
bash-3.2$ ./test
All the elements are zero.
Run Code Online (Sandbox Code Playgroud)
我试图弄清楚为什么空容器为此操作返回true.此问题可能与以下内容有关: 当list为空时,std :: list:begin()的行为
但是我无法找到这个特定问题的正确答案.
感谢您的时间.
std::all_oftrue如果范围为空,则返回.从25.2.1全部
template <class InputIterator, class Predicate>
bool all_of(InputIterator first, InputIterator last, Predicate pred);
Run Code Online (Sandbox Code Playgroud)
返回:
trueif[first,last)为空或者是否pred(*i)为范围内的true每个迭代器,否则返回.i[first,last)false
我试图弄清楚为什么空容器为此操作返回true.
因为这是真的.容器中有零个元素不等于0.因此,所有元素都满足等于零的条件.它们也碰巧满足不等于0的条件,因为容器中有零元素等于0,所以反向谓词也可以.
事实上,容器中的零元素根本不满足任何条件,因此容器的所有元素都满足任何条件.因此传递给任何谓词all_of都会导致all_of返回true空范围.甚至是一个只返回的谓词,true或者false不论其论证如何.