【问题标题】:How to check whether an unsigned char vector contains all null characters如何检查无符号字符向量是否包含所有空字符
【发布时间】:2020-12-03 07:57:23
【问题描述】:

我需要检查我的向量是否包含所有空字符并根据该结果执行一些操作。我在 Stack Overflow 中发现了几个问题,但它们并不完全符合我的要求。

我能想到的决定一个全为空字符的向量的一种解决方案是:

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

如果有更好的方法,请分享你的想法。

完整代码为:

文件1.cpp:

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

文件2.cpp:

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

在此之后,在 File1.cpp 中,我只得到 Buffer,其中填充了有效数据或 '\0'。

这是在 C++ 98 中

【问题讨论】:

  • 您的第一个 sn-p 代码只检查第一个字符。为什么不用clear() 向量,或者使用std::optional&lt;std::vector&lt;unsigned char&gt;&gt;
  • 不要对容器使用memset,使用std::fill
  • @Botje 由于来自其他文件的一些依赖关系,我不应该编辑该缓冲区
  • @LouisGo 我使用了memset(),因为在 File2.cpp 中,缓冲区被视为unsigned char *

标签: c++ vector null c++98


【解决方案1】:

您可以使用std::all_of() 算法检查是否所有元素都满足条件。 我希望你也看到std::any_of()std::none_of()

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

对于 C++11 不可用的情况,您可以像这样实现 any_of:

bool is_clear=true;
for(size_t i=0; i<Buffer.size(); ++i)
{
  if(Buffer[i]!=0)
  {
    is_clear=false;
    break;
  }
}

【讨论】:

  • @explorer2020,然后使用循环并检查每个元素是可能的。我为它编辑了答案,但我不确定它是否适用于 C++98,因为我不习惯标准。
  • 在我的情况下 if(Buffer[0] == '\0') {} 比循环更好,因为我在向量中有大量数据。但是您的回答很有帮助,因此被接受为答案:) 谢谢。
  • @explorer2020,很高兴听到这对您有帮助。也许你可以在 C++98 中找到更好的选择,因为我不习惯标准。
猜你喜欢
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
  • 2019-06-07
相关资源
最近更新 更多