![](/img/trans.png)
[英]How to return null from a function whose return type is map in Visual C++?
[英]How to return nullptr equivalent from a C++ function whose return type is pair?
pair<int, int> findEmpty(int bo[9][9], int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(bo[i][j]==0){
return (make_pair(i, j));
}
}
}
//return nullptr;
}
如果 nullptr 不能返回,有什么替代方法?
使用optional<T>
類型表示可能不存在的 state。
如果你使用 C++17 這可以用std::optional<T>
來完成,如果你使用 Boost 然后boost::optional<T>
等等。你甚至可以實現你自己的optional
版本。 關鍵是使用一種語義類型來指示可能存在或不存在值。
使用 C++17 中的std::optional
,您的代碼變為:
optional<pair<int, int>> findEmpty(int bo[9][9], int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(bo[i][j]==0){
return make_pair(i, j);
}
}
}
return nullopt;
}
盡管您可以通過返回類似標記的值(例如一對(-1, -1)
來解決此問題,但這不是推薦的做法。 這會強制檢查調用者上的特定哨兵值,這很容易被遺漏或遺忘——並且可能導致錯誤的哨兵值進入其他可能永遠不會期望負值的算術或間接運算。
使用語義類型來傳達可空性有助於防止此類錯誤。
在 C++17 及更高版本中,您可以返回std::optional
,例如:
std::optional<std::pair<int, int>> findEmpty(int bo[9][9], int n){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if (bo[i][j] == 0){
return std::make_pair(i, j);
}
}
}
return std::nullopt;
}
auto ret = findEmpty(...);
if (ret)
{
// use ret.value as needed...
}
或者,您可以返回一個pair<bool, pair<int,int>>
,其中bool
指示內部pair
是否有效:
std::pair<bool, std::pair<int, int> > findEmpty(int bo[9][9], int n){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if (bo[i][j] == 0){
return std::make_pair(true, std::make_pair(i, j));
}
}
}
return std::make_pair(false, std::make_pair(-1, -1));
}
std::pair<bool, std::pair<int, int> > ret = findEmpty(...);
if (ret.first)
{
// use ret.second as needed...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.