我试图set.insert (key)
用作条件,如果正确插入了密钥(这意味着密钥在集合中不存在),那么它应该继续执行某种代码。例如,类似:
if (set.insert( key )) {
// some kind of code
}
这是允许的吗?因为编译器抛出这个错误:
conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal
我试图set.insert (key)
用作条件,如果正确插入了密钥(这意味着密钥在集合中不存在),那么它应该继续执行某种代码。例如,类似:
if (set.insert( key )) {
// some kind of code
}
这是允许的吗?因为编译器抛出这个错误:
conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal
采用单个键值的 insert 版本应返回 a std::pair<iterator,bool>
,其中 bool 指示是否进行了插入。true 值表示已插入该值,false 表示该值已存在。所以你的条件看起来像这样:
if( set.insert( key ).second ) {
// code
}
set::insert 返回一对,试试这个:
if( set.insert( key ).second ) {
// some kind of code
}
其他答案建议只使用“.second”,这将起作用 - 但如果您需要执行的处理使用集合中的现有条目,那么您可以存储插入的完整结果:
std::pair<std::set<key>::iterator, bool> iResult = set.insert (key);
if (iResult.second) {
// some kind of code - insert took place
}
else {
// some kind of code using iResult.first, which
// is an iterator to the previous entry in the set.
}