查找std::set中的元素
Finding elements in std::set
假设我有一个std::set
,我如何发现集合中的一个元素是否在另一个元素之前。例如,像这样-
bool before(const std::set &s, const int first, const int second) const {
auto it_first = s.find(first);
auto it_second = s.find(second);
return it_first <= it_second;
}
上面的代码不起作用,因为没有为双向迭代器定义<=
,但是如何做这样的事情呢?
A set
按operator<
排序(默认)。比较器本身可以通过key_comp
或value_comp
检索。因此,如果两个元素都在集合中,则顺序由元素本身定义—不需要迭代器:
return s.key_comp()(first, second);
如果一个或两个都不在集合中,则取决于在这些情况下您想要做什么:
if (s.count(first)) {
if (s.count(second)) {
return s.key_comp()(first, second);
}
else {
/* no second */
}
}
else {
/* no first, possibly second */
}
如果你想寻找比std::set
更通用的解决方案,这个方法将适用于任何具有forward
迭代器的容器:
template <class T>
bool before( const T &cont, typename T::const_iterator first, typename T::const_iterator second )
{
for( auto it = cont.begin(); true; ++it ) {
if( it == first ) return true;
if( it == second ) return false;
}
}
假设first
和second
是有效的迭代器。现在您可以为std::set
和std::map
提供更优的专门化:
return cont.key_comp()( *first, *second );
,对于具有随机访问迭代器的容器:
return first < second;
相关文章:
- 对于set上的循环-获取next元素迭代器
- set::find 查找不存在的元素
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 如何从 std::set 绘制 n 个元素的样本
- 从 std::set 中删除元素,同时在 C++17 中迭代该元素
- 如何在对数时间内访问 c++ std::set 中的第 k 个元素?
- 语言的哪一部分禁止更改 std::set 的元素
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 在 std::set 中查找 std::vector 的元素
- 创建 std::set 只复制一个元素,如何解决这个问题?
- 为什么 std::set 遍历所有元素的速度较慢?
- 为什么在查找元素时需要使用 set.find(x) != set.end()
- 直接访问 STL "set"元素
- 新元素将在std :: set中插入哪里
- std :: set and std :: unordered_set构造元素与emplace()如何
- 通过与不同类型的值进行自定义比较来查找 std::set 的元素
- 删除 std::set<Node *> 中的元素的正确方法
- 如何使用反向迭代器从“std::set”中删除元素
- 给定一个 std::set::iterator,获取一个指向下一个元素的迭代器
- 无法将 std::set 中的元素迭代器插入到 std::list