我正在尝试使用set.insert (key)
作为条件,如果正确插入了密钥(意味着该密钥尚未存在于集合中),那么它应该继续并执行某种代码。例如,像:
if (set.insert( key )) {
// some kind of code
}
这是允许的吗?因为编译器抛出了这个错误:
conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal
答案 0 :(得分:14)
采用单个键值的insert版本应返回std::pair<iterator,bool>
,其中bool指示是否进行了插入。值true表示已插入值,false表示该值已存在。因此,您的条件将如下所示:
if( set.insert( key ).second ) {
// code
}
答案 1 :(得分:2)
set :: insert返回一对,试试这个:
if( set.insert( key ).second ) {
// some kind of code
}
答案 2 :(得分:1)
其他答案建议只使用'.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.
}