![](/img/trans.png)
[英]How to return nullptr equivalent from a C++ function whose return type is pair?
[英]How to return null from a function whose return type is map in Visual C++?
我想從返回類型為map的函數中返回空數據。
這是我的代碼。
map<string, string> something_to_do(string something) {
// something to do..
// if above code is something wrong, it should return null.
return null;
}
但是,似乎沒有類型轉換可以在地圖庫中返回null。
我該怎么做?
(對不起我的英語不好。。。)
作為替代方案,您可以在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;
}
如果該函數返回一個map
,則必須返回一個map
-您不能返回nullptr
(當然,這是一個空map
,但這與您將得到的接近)。 也許您正在尋找std::optional
以便您可以讓函數返回一個可能存在或可能不存在的可選映射?
我認為拋出異常可以更好地處理您正在尋找的功能。
這樣,您可以照常進行,但是如果出現問題(如您在注釋中提到的那樣),則您想拋出一個異常並讓任何客戶端代碼相應地處理該異常。 請參閱此SO帖子 。
它使您可以編寫簡單明了的代碼,而無需為運行代碼的每種可能情況返回自定義類型。 它還消除了僅為了處理任何錯誤而檢查返回的某些值的需要。
要調用該函數並處理錯誤,您只需將方法調用包裝在try-catch
塊中:
來自@nsanders的原始答案
try { compare( -1, 3 ); } catch( const std::invalid_argument& e ) { // do stuff with exception... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.