c++ - 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 }
解决方案
由于没有进一步的 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 }
请注意,检查所有字段并非绝对必要。我认为只检查rows
或data.size()
应该也可以,因为有效的图像应该总是包含一些行或数据。
推荐阅读
- python - 结帐表格未保存
- sql - 如何在 couchbase 中添加一个键值,其中该值是从文档中已经存在的键值派生的
- python-3.x - SQLAlchemy:反映现有数据库的表无法正常工作
- visual-studio-code - 我的笔记本电脑在使用 vs code 时被关闭了。我可以以某种方式撤消我的文件更改吗?它没有连接到git
- android - Android Studio 显示的 editText 属性很少
- python - 使用 Selenium python 查找元素并发送密钥(blogspot 评论)
- php - PDFLib 表 PHP
- android-source - 如果我们将 SELinux 设置为 Permissive 模式会发生什么
- javascript - AFrame+Three.js 在每个有几个三角形的多个网格和每个有很多三角形的几个网格之间有什么更高的性能?
- php - 当我输入 IP 地址作为 URL 时,WordPress 没有加载,我只得到默认的 Ubuntu 页面(Ubuntu 18.04)