c++ - 查找不在 std::set 中的第一个值最小-最大
问题描述
如何找到h
不在结果std::set<int> ids
范围内的第一个值[0, *ids.rbegin() + 1]
。
我看到这是一个相当简单的问题,但我还没有找到任何匹配的问题。基本上我想要倒置的集合,ids
以便我可以使用它们。
到目前为止,我有以下内容:
#incldue <set>
std::set<int> ids;
int h = 0;
for(; !ids.empty() && (h <= *ids.rbegin() + 1); ++h) {
if(!ids.count(h)) {
break;
}
}
// h is now smallest value not in ids.
我怀疑这会进一步改进,例如不需要循环?
@edit:澄清集合中的值:在我的用例中,算法生成的值被插入到集合中。我真的应该说std::set<unsigned int>
。我很高兴就这个问题进行了如此多的讨论!
解决方案
由于 astd::set
的元素已排序,因此您可以使用std::adjacent_find
.
std::adjacent_find(set.begin(), set.end(), [](int a, int b){ return a+1 != b; } );
这将返回一个指向第一个元素 的迭代器,该元素a
后面没有值a+1
。或者set.end()
如果没有这样的价值。
示例用法:
std::set<int> ids { -2, -1, 0, 1, 2, 4, 5, 6 };
// This code assumes a non-empty set, since the range in the question requires same
if ( *ids.begin() > 0 )
{
// Special case for [0
std::cout << 0;
}
else
{
auto res = std::adjacent_find(ids.begin(),
ids.end(),
[](int a, int b){ return a+1 != b; } );
if ( res == ids.end() )
{
// Special case for *ids.rbegin() + 1]
std::cout << *ids.rbegin() + 1;
}
else
{
// Print the value that should have followed this one.
std::cout << *res + 1;
}
}
输出:
3
推荐阅读
- android - Firebase:如何检查文档写入是否成功
- java - mvn install - 使用 IntelliJ 版本 2020.2 的 org.jfree.chart 构建错误
- python-3.x - python3中的PyGTK、PyGObject和Pgi
- docker - “。”是什么意思?在“docker run .”中呢?
- vim - 过滤要显示的行
- java - 如何在Java OpenCV中删除轮廓内的轮廓?
- node.js - POST 路由在本地主机上工作但不在服务器上
- azure - Azure Data Studio - 更改 Azure SQL 数据库默认连接类型的方法?
- sql - 将地址字符串分成多列
- java - 如何连续计算位置更新之间的距离以获得总距离