C++ 空容器迭代器行为

标签 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

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

感谢您的宝贵时间。

最佳答案

如果范围为空,

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 if pred(*i) is true for every iterator i in the range [first,last), and false otherwise.

关于C++ 空容器迭代器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25600484/

相关文章:

docker - 按需启动容器

C++ 容器和右侧

c++ - Qt 中的 os.path.join()?

c++ - 使用 lib.a 文件调试链接错误

image - 如何在 Flutter 中拉伸(stretch)图像以适合整个背景(100% 高度 x 100% 宽度)?

docker - 如何使用kubernetes生成容器的多个实例?

C++循环包含

c++ - 找出由 libavcodec/h264 解码的帧中的伪影级别

c++ - 如何在 Debian 上编译我的 C++ 项目?

Bash 重定向不适用于容器创建 : "can' t create/dev/tcp/<ip>/<port>: nonexistent directory"