c ++空容器迭代器行为

时间:2014-09-01 07:06:41

标签: c++ containers

我只是尝试初始化一个容器,它碰巧是空的,并且遇到了以下现象:

#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

但是我找不到这个特定问题的正确答案。

感谢您的时间。

3 个答案:

答案 0 :(得分:6)

如果范围为空,则

std::all_of返回true。来自 25.2.1全部

template <class InputIterator, class Predicate>
bool all_of(InputIterator first, InputIterator last, Predicate pred);
  

如果true为空或[first,last)pred(*i),则返回true   i范围内的每个迭代器[first,last),否则为false

答案 1 :(得分:5)

  

我试图找出为什么空容器为此返回true   操作

因为 是真的。容器中有零个元素不等于0.因此所有元素满足等于零的条件。它们都碰巧满足不等于0的条件,因为容器中有零元素等于0,所以反向谓词也可以。

实际上,容器中的零元素根本不满足任何条件,因此容器的所有元素都满足任何条件。因此,传递给all_of的任何谓词都会导致all_of返回true一个空范围。即使是只返回truefalse的谓词,也不论其参数如何。

答案 2 :(得分:3)

这是std::all_of算法的正确行为。

  

返回值:如果一元谓词为所有元素返回true,则返回true   范围,否则为假。 如果范围为空,则返回true。