简体   繁体   English

如何从Visual C ++中返回类型为map的函数返回null?

[英]How to return null from a function whose return type is map in Visual C++?

I want to return null data from a function that return type is map. 我想从返回类型为map的函数中返回空数据。

Here is my code. 这是我的代码。

map<string, string> something_to_do(string something) { 
    // something to do..
    // if above code is something wrong, it should return null.
    return null;
}

But, there seems to be no type casting to return null in map library. 但是,似乎没有类型转换可以在地图库中返回null。

How can I do it? 我该怎么做?

(I'm sorry my awful English..) (对不起我的英语不好。。。)

as an alternative you can in C++17 use instead std::optional 作为替代方案,您可以在C ++ 17中使用std::optional

std::optional<std::map<string,string>> something_to_do(string something) {
  std::map<std::string,std::string> yourmap;
  yourmap["a"] = "b";
  ...
  return yourmap;

  // or 
  // return std::null_t;
}

...

auto d = something_to_do(something);
if (d)
{
  auto& m = d.value();
  std::cout << m["a"] << std::endl;
}

If the function returns a map you must return a map - you cannot return nullptr (an empty map , sure, but that's as close as you'll get). 如果该函数返回一个map ,则必须返回一个map -您不能返回nullptr (当然,这是一个空map ,但这与您将得到的接近)。 Maybe you are looking for std::optional so you can have your function return an optional map that may or may not be there? 也许您正在寻找std::optional以便您可以让函数返回一个可能存在或可能不存在的可选映射?

I think the functionality you are looking for would be better handled by throwing an exception. 我认为抛出异常可以更好地处理您正在寻找的功能。

That way you can proceed as normally, but if something goes wrong like you allude to in your comment, then you want to throw an exception and have any client code handle the exception accordingly. 这样,您可以照常进行,但是如果出现问题(如您在注释中提到的那样),则您想抛出一个异常并让任何客户端代码相应地处理该异常。 See this SO post . 请参阅此SO帖子

It allows you to write straight-forward code without having custom types to return for every possible situation of your running code. 它使您可以编写简单明了的代码,而无需为运行代码的每种可能情况返回自定义类型。 It also eliminates the need to check for certain values being returned just to handle any errors. 它还消除了仅为了处理任何错误而检查返回的某些值的需要。

To call the function and handle the error, you would simply wrap the method call in a try-catch block: 要调用该函数并处理错误,您只需将方法调用包装在try-catch块中:

from @nsanders' orginal answer 来自@nsanders的原始答案

 try { compare( -1, 3 ); } catch( const std::invalid_argument& e ) { // do stuff with exception... } 

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

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