0

I need to check whether my vector contains all null characters and perform some operation based on that result. I found couple of questions in Stack overflow but they are not exactly matching my requirement.

One solution that I can think of to decide a vector with all null characters is:

if(Buffer[0] == '\0') {
 std::cout<<"vector contains all NULL characters";
}

If there is any better way for this, please share your idea.

Complete code is:

File1.cpp:

std::vector<unsigned char> Buffer(BufferSize, 0);

File2.cpp:

try
{
    // do some operation, if no exception then fill the buffer
    // if exception then go to catch block
}
catch(...)
{
    memset(Buffer, '\0', BufferSize); 
}

After this, in File1.cpp I just get Buffer, filled with valid data or '\0'.

This is in C++ 98

1 Answers1

3

You can use std::all_of() algorithm to check if all of the elements meets a condition. I hope you see std::any_of() and std::none_of() also.

int BufferSize = 30;
vector<unsigned char> Buffer(BufferSize, 0);
bool is_clear = std::all_of(Buffer.cbegin(), Buffer.cend(), [](unsigned char c) {return c == 0; });

For the cases where C++11 is not available you can implement any_of like this:

bool is_clear=true;
for(size_t i=0; i<Buffer.size(); ++i)
{
  if(Buffer[i]!=0)
  {
    is_clear=false;
    break;
  }
}
John Park
  • 1,644
  • 1
  • 12
  • 17
  • @explorer2020, Then using loop and checking each of element is possible. I edited my answer for it, but I'm not sure it works in C++98 because I'm not used to the standard. – John Park Aug 13 '20 at 14:09
  • In my case if(Buffer[0] == '\0') {} is better than the loop as I have huge data in the vector. But your answer is helpful, so accepted as the answer :) Thank you. – explorer2020 Aug 14 '20 at 06:29
  • @explorer2020, Good to hear that it was helpful for you. Maybe you can find better option in C++98, as I'm not used to the standard. – John Park Aug 14 '20 at 06:35