To check if a list contains all the elements of another list in C++, you can iterate over one list and check the presence of each element in the other list using nested loops.
In this example,
list1
and list2
with different values.list2
and check if each element is present in list1
.list2
are found in list1
, we conclude that list1
contains all elements of list2
.#include <iostream>
#include <list>
int main() {
std::list<int> list1 = {1, 2, 3, 4, 5};
std::list<int> list2 = {2, 4};
bool result = true;
for (int num : list2) {
if (std::find(list1.begin(), list1.end(), num) == list1.end()) {
result = false;
break;
}
}
std::cout << "List 1 contains all elements of List 2: " << std::boolalpha << result << std::endl;
return 0;
}
List 1 contains all elements of List 2: true
In this example,
list1
and list2
with different values.list2
and check if each element is present in list1
.list2
is not found in list1
, we conclude that list1
does not contain all elements of list2
.#include <iostream>
#include <list>
int main() {
std::list<int> list1 = {1, 2, 3, 4, 5};
std::list<int> list2 = {2, 4, 6};
bool result = true;
for (int num : list2) {
if (std::find(list1.begin(), list1.end(), num) == list1.end()) {
result = false;
break;
}
}
std::cout << "List 1 contains all elements of List 2: " << std::boolalpha << result << std::endl;
return 0;
}
List 1 contains all elements of List 2: false
In this tutorial, we learned How to check if a List contains all the elements of Another List in C++ language with well detailed examples.