受當前最受歡迎的question concerning getting the larger of two values in C#頂級答案的啓發。比較兩個整數值指向
考慮接受兩個整數指針並返回一個指針的函數。這兩個指針可能是nullptr
。
const int* max(const int* a, const int* b);
如果a或b是nullptr
則返回非空指針。如果兩者都是nullptr
,則返回nullptr
。
如果兩個都是有效指針返回max(*a, *b);
。
當前最upvoted答案爲C#問題是
int? c = a > b ? a ?? b : b ?? a;
詮釋?表示可空值,與指針不同。
這是如何在C++中以優雅和慣用的方式表達的?
我立即嘗試是沿着
const int* maxp(const int* a, const int* b){
if (!a) return b;
if (!b) return a;
return &std::max(*a, *b);
}
這裏暫時沒有問題,'std :: max'返回對更大元素的引用。我認爲你的代碼大大優於任何不可讀的操作符。 –
'std :: optional'是(將會)更好地匹配'Nullable ',它支持相同的事情。 'auto c = b
chris