首页 > 解决方案 > C++ 检查结构是否为空

问题描述

您好有一个外部库函数,它具有以下功能:

struct ImageData {
  int rows;
  int cols;
  int max_val;
  std::vector<int> data;
};

/// Reads from a pgm image from ascii file. Returns empty ImageData if the path
/// is not found or any errors have occured while reading.
ImageData ReadFromPgm(const std::string& file_name);

在调用此函数后进行一些处理时,我需要一种方法来判断“空 ImageData”是什么,类似于:

ImageData read_from_pgm = ReadFromPgm(some_file);
if (read_from_pgm is empty) { //do something }
else{ //do something else }

标签: c++

解决方案


由于没有进一步的 API 文档,我们只能做一个假设。最有可能的是, 空 ImageData表示ImageData类型 ( ImageData id = { });的默认(初始化)值。这意味着所有字段的默认值。在这种情况下,您可以做一个简单的检查:

ImageData read_from_pgm = ReadFromPgm(some_file);
if (read_from_pgm.rows == 0
    && read_from_pgm.cols == 0
    && read_from_pgm.max_val == 0
    && read_from_pgm.data.size() == 0)
{ //Image is empty }

请注意,检查所有字段并非绝对必要。我认为只检查rowsdata.size()应该也可以,因为有效的图像应该总是包含一些行或数据。


推荐阅读