Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ empty container iterator behaviour

Tags:

c++

containers

I just tried to initialised a container, which happened to be empty and came across the following phenomenon:

#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;
}

compiling with:

clang++ -std=c++11 -stdlib=libc++ -o test test.cpp

resulted in:

bash-3.2$ ./test
All the elements are zero.

I am trying to figure out why an empty container returns true for this operation. This problem might be related to: Behaviour of std::list:begin() when list is empty

However I could not find a proper answer to this particular question.

Thank you for your time.

like image 799
Vincent Avatar asked Jan 19 '26 14:01

Vincent


1 Answers

std::all_of returns true if the range is empty. From 25.2.1 All of

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.

like image 164
juanchopanza Avatar answered Jan 21 '26 04:01

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!