繁体   English   中英

用布尔类型包装返回值

[英]Wrap the return values with boolean type

我正在尝试编写一个具有多个返回值的函数。 如果路径中没有图像,我需要处理这种情况。 我怎样才能做到这一点?

我试过使用地图。 但它更多的是键,值对是我认为的(C++ 新手)。

下面是我的代码:

tuple<Mat, Mat> imageProcessing(boost::filesystem::path pickPath){
    Mat img1, img2;
    // Check if file exists, if not return NULL
    if (!boost::filesystem::is_regular_file(pickPath)) {
        return make_tuple(NULL, NULL); 
    }

        imageFile = imread(pickPath.string());

        // Preprocess code (return 2 mat files)

        return make_tuple(img_1, img_2);
   }



int main(){
    path = "img.jpeg"
    tie(img1, img2) = imageProcessing(path);
}

如果您想要连续的对象集合,请使用std::vector ,如果您的函数保证仅返回唯一结果,请使用std::set

您的方法还应该优雅地处理错误。 一般来说,在 C++ 中有两种方法:

  1. 例外。 当您的函数遇到来自第 3 方库或任何其他意外情况的错误数据/错误代码时,您可以抛出异常,函数调用者需要编写代码来处理它。 您的方法可能如下所示:
std::vector<Mat> ProcessImages(const boost:filesystem::path filePath)
{
   if (!boost::filesystem::is_regular_file(pickPath)) {
       throw std::invalid_argument("file does not exist"!); //probably there's a better exception you could throw or you can define your own.
   }
...

调用者看起来像这样:

  try{
        auto images = ProcessImage(myFilePath)
  }
  catch(const std::invalid_argument& e ) { 
     // write something to console, log the exception, terminate your process... choose your poison.
  }
  1. 返回错误代码。 有几种方法可以做到这一点 - 返回一个元组,其中第一项是错误代码,第二项是向量,或者通过引用传递向量并仅返回错误代码:
// if successful the function will return 0.
enum ErrorCode
{
  Successful = 0,
  InvalidArgs = 1,
  ...
}

ErrorCode ProcessImages(const boost:filesystem::path filePath, std::vector<Mat>& outImages)
{
   if (!boost::filesystem::is_regular_file(pickPath)) {
   {
    return InvalidArgs;
   }

   imageFile = imread(pickPath.string());

   outImages.insert(img1);
   outImages.insert(img2);

   return Successful;
}

int main(){
    path = "img.jpeg"
    std::vector<Mat> images;
    auto result = ProcessImages(path, images);
    if (result != Successfull)
    {
      //error
    }
}

我认为你可以使用vector<Mat>并将所有图像推送到这个向量并返回它。 然后你可以在调用函数后检查这个向量的长度。 如果它为零,则意味着您没有推送任何内容(如果在路径中找不到文件)。 否则,根据需要从矢量中提取所有图像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM