To check if a set contains all the items of another set in C++, you can iterate through the elements of the second set and use the find
method of the first set.
In this example,
setA
and setB
containing some elements.setB
and check if each element exists in setA
using the find
method.setB
is not found in setA
, we conclude that setA
is not a subset of setB
.setA
is a subset of setB
.#include <iostream>
#include <set>
int main() {
std::set<int> setA = {1, 2, 3, 4, 5};
std::set<int> setB = {2, 3};
bool isSubset = true;
for (const auto& elem : setB) {
if (setA.find(elem) == setA.end()) {
isSubset = false;
break;
}
}
std::cout << "Is setA a subset of setB? " << (isSubset ? "true" : "false") << std::endl;
return 0;
}
Is setA a subset of setB? true
In this example,
setA
and setB
containing some elements.setA
and check if each element exists in setB
using the find
method.setA
is not found in setB
, we conclude that setA
is not a superset of setB
.setA
is a superset of setB
.#include <iostream>
#include <set>
int main() {
std::set<int> setA = {1, 2, 3, 4, 5};
std::set<int> setB = {2, 3};
bool isSuperset = true;
for (const auto& elem : setA) {
if (setB.find(elem) == setB.end()) {
isSuperset = false;
break;
}
}
std::cout << "Is setA a superset of setB? " << (isSuperset ? "true" : "false") << std::endl;
return 0;
}
Is setA a superset of setB? true
In this tutorial, we learned How to check if a Set contains all the items of Another Set in C++ language with well detailed examples.