To check if two lists are equal in C++ using std::list
, you can iterate over both lists and compare each element.
In this example,
list1
and list2
with equal values.list1
and list2
.#include <iostream>
#include <list>
int main() {
std::list<int> list1 = {1, 2, 3};
std::list<int> list2 = {1, 2, 3};
bool equal = true;
if (list1.size() != list2.size()) {
equal = false;
}
else {
auto it1 = list1.begin();
auto it2 = list2.begin();
while (it1 != list1.end()) {
if (*it1 != *it2) {
equal = false;
break;
}
++it1;
++it2;
}
}
std::cout << std::boolalpha << "Are the lists equal? " << equal << std::endl;
return 0;
}
Are the lists equal? true
In this example,
list1
and list2
with different values.list1
and list2
.#include <iostream>
#include <list>
int main() {
std::list<int> list1 = {1, 2, 3};
std::list<int> list2 = {1, 2, 4};
bool equal = true;
if (list1.size() != list2.size()) {
equal = false;
}
else {
auto it1 = list1.begin();
auto it2 = list2.begin();
while (it1 != list1.end()) {
if (*it1 != *it2) {
equal = false;
break;
}
++it1;
++it2;
}
}
std::cout << std::boolalpha << "Are the lists equal? " << equal << std::endl;
return 0;
}
Are the lists equal? false
In this tutorial, we learned How to check if Two Lists are Equal in C++ language with well detailed examples.