In C++, you can sort both lists and then compare them to check if they have the same elements regardless of order.
In this example,
list1
and list2
with the same set of elements.sort()
function from the algorithm
library.#include <iostream>
#include <list>
#include <algorithm>
int main() {
std::list<int> list1 = {1, 2, 3};
std::list<int> list2 = {3, 2, 1};
list1.sort();
list2.sort();
bool result = (list1 == list2);
std::cout << "Do the lists have the same elements? " << std::boolalpha << result << std::endl;
return 0;
}
Do the lists have the same elements? true
In this example,
list1
and list2
with different sets of elements.sort()
function from the algorithm
library.#include <iostream>
#include <list>
#include <algorithm>
int main() {
std::list<int> list1 = {1, 2, 3};
std::list<int> list2 = {4, 5, 6};
list1.sort();
list2.sort();
bool result = (list1 == list2);
std::cout << "Do the lists have the same elements? " << std::boolalpha << result << std::endl;
return 0;
}
Do the lists have the same elements? false
In this tutorial, we learned How to check if Two Lists have Same Elements (Regardless of Order) in C++ language with well detailed examples.