在c++中是否有NULL等价的pair ?
Is there a NULL equivalent for pairs in C++?
如果我在c++中有一个未分配的对,我想使用什么而不是NULL ?
例如,假设我有如下的(伪)代码:pair<int,int> bestPair; //Global variable
updateBestPair(vector<int> a, vector<int> b) {
bestPair = NULL;
for (/* loop through a and b */) {
if (/* pair(a,b) is better than bestPair and better than some baseline */)
bestPair = make_pair(a,b);
}
if (bestPair != NULL) //Found an acceptable best pair
function(bestPair);
else
cout<<"No acceptable pairs found"<<endl;
}
号在c++中对是否有NULL等价?
如果我在c++中有一个未分配的对,我想用什么代替NULL ?
这里有几个选项:
可以使用指向pair的指针,可以设置为NULL;这可能不是最好的解决方案(因为您显然不需要指针)
你可以使用
boost::optional<std::pair<int,int>>
;你可以(也许应该)重写你的代码,不使用全局变量
你可以重组你的控制流,以避免检查一个有效的对作为一个单独的步骤:
pair<int,int> bestPair; //Global variable updateBestPair(vector<int> a, vector<int> b) { // not needed // bestPair = NULL; //loop through a and b if (/* pair(a,b) is better than bestPair and ... */) { bestPair = make_pair(a,b); function(bestPair); } else cout<<"No acceptable pairs found"<<endl; }
你可以选择一个人工值来表示"invalid pair value":
// use as constant, wherever you used NULL before const auto invalid_pair = std::make_pair( std::numeric_limits<int>::max(), std::numeric_limits<int>::max());
你可以使用布尔标志:
pair<int,int> bestPair; //Global variable updateBestPair(vector<int> a, vector<int> b) { bool initialized = false; //loop through a and b if (/* pair(a,b) is better than bestPair and ... */) { bestPair = make_pair(a,b); initialized = true; } if(initialized) function(bestPair); else cout<<"No acceptable pairs found"<<endl; }
您可以使用自定义解决方案(类似于boost::可选包装或不)
No。c++对象不能为" null "
(即使指针是对象,也不能被" null "!)这是令人困惑的,因为它们的值可能被设置为空指针值,我们过去有时通过名为NULL
的宏获得;然而,这与指针本身的"空"是不一样的。呃,anyway…)
我推荐boost::optional
,或者重新考虑拥有一个全局变量的想法,可以是"有一个有用的值"或"没有一个有用的值"。如果它没有有用的价值,存在的意义是什么?
不,那不可能。您可以使用一个额外的变量来指示对的有效性(您有一个对)。
相关文章:
- 是否需要删除包含对象的"pair"?
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 如何在 c++ 中'NULL'字符串
- c++使用foreach使数组为null
- 当使用通配符和null指针调用函数时,对输出的说明
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- 如何在映射中返回null
- 为什么返回 NULL 不会破坏函数?
- 构造函数中的 QQuickItem 父项 null
- 对 pair<pair<int,int>pair<int,int unordered_map进行哈希处理>>
- 检查字符串是否"null" C++
- fopen 在 gdb 中返回 NULL
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- what(): basic_string::_M_construct null not valid
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 为什么要从main()返回NULL?
- 在c++中是否有NULL等价的pair ?