[英]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++ 中有两种方法:
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.
}
// 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.