[英]How to look for an element inside a set of sets in C++?
Following is my code:以下是我的代码:
set<set<int,greater<int>>> output;
set<int,greater<int>> k;
k.insert(5);
output.insert(k);
Now how do I find out if element 5 is present in my 'output' set or not?现在我如何确定元素 5 是否存在于我的“输出”集中?
And how do I find out which set, inside my 'output' set, the element 5 belongs to?以及如何找出元素 5 在我的“输出”集中属于哪个集合?
Use a simple for
loop:使用一个简单的
for
循环:
size_t ii = 0;
for (const auto& inner : output) {
if (inner.count(5))
std::cout << "found in set " << ii << std::endl;
++ii;
}
There's a pre C++20 and a C++20 (using ranges) solution有一个 pre C++20 和一个 C++20(使用范围)解决方案
Pre-C++20 I'm using std::find_if
and set::find
. Pre-C++20 我正在使用
std::find_if
和set::find
。 C++20 I'm using std::ranges::find_if
and set::contains
. C++20 我正在使用
std::ranges::find_if
和set::contains
。 For the C++20 I'm also using std::optional
std::reference_wrapper
return type.对于 C++20,我也使用
std::optional
std::reference_wrapper
返回类型。 And concepts, so it's a generic solution applicable to all sets and maps.和概念,所以它是适用于所有集合和地图的通用解决方案。
#include <set>
#include <algorithm>
template<typename T, typename Comp = std::less<T>>
std::set<T, Comp> const* findInSetOfSets(std::set<std::set<T, Comp>> const& setOfSets, T const& value) {
auto const it = std::find_if(cbegin(setOfSets), cend(setOfSets),
[&](std::set<T, Comp> const& set) { return set.find(value) != end(set); } );
if (it != cend(setOfSets)) return &*it;
return nullptr;
}
#include <optional>
#include <functional>
#include <type_traits>
template<typename T, typename U>
concept hasContains = requires(T& t, U& u) {
{ t.contains(u) } -> std::same_as<bool>;
};
template<std::ranges::input_range R, typename T,
typename U = std::remove_reference<R>::type::value_type>
requires hasContains<U, T>
[[nodiscard]] auto findCpp20(R&& r, T const& value) noexcept
->std::optional<std::reference_wrapper<U const>> {
auto it = std::ranges::find_if(r,
[&](U const& u) { return u.contains(value); } );
if (it != std::ranges::end(r)) return *it;
return std::nullopt;
}
#include <cstdio>
int main(){
std::set<std::set<int,std::greater<int>>> output;
std::set<int,std::greater<int>> k;
k.insert(5);
output.insert(k);
auto setPtr = findInSetOfSets(output, 5);
if (setPtr != nullptr) printf("set found!\n");
auto optionalSet = findCpp20(output, 5);
if (optionalSet.has_value()) printf("set found!\n");
}
Here's a boolean function that looks for element p inside a set of sets s这是一个布尔函数,它在一组集合s中查找元素p
bool findelem(int p, set<set<int>> const& s)
{
for (auto itr1= s.cbegin(); itr1 != s.cend(); ++itr1) {
for (auto itr2 = itr1->cbegin(); itr2 != itr1->cend(); ++itr2) {
if (*itr2==p) {
return true;
}
}
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.