Compare two lists in C++
Compare two lists in C++
The '==' operator in C++ can be used to compare two lists. It will return 'true' if the lists are equal and 'false' if they are not. Here is an illustration of how to compare two lists in C++:
#include <iostream> #include <list> int main() { std::list<int> list1{1, 3, 5, 7}; std::list<int> list2{1, 3, 5, 7}; std::list<int> list3{1, 2, 4, 5, 8}; if (list1 == list2) { std::cout << "LIST 1 AND LIST 2 ARE EQUIVALENT" << std::endl; } else { std::cout << "LIST 1 AND LIST 2 ARE NOT EQUIVALENT" << std::endl; } if (list1 == list3) { std::cout << "LIST 1 AND LIST 3 ARE EQUIVALENT" << std::endl; } else { std::cout << "LIST 1 AND LIST 3 ARE NOT EQUIVALENT" << std::endl; } return 0; }
OUTPUT:
It is a consideration that for this method to function, both lists must have elements of the same type and in the same order.
You must use a different method if you want to compare lists that contain various element types or if you want to compare the lists without taking the element order into account.
ANOTHER APPROACH:
#include <iostream> #include <vector> bool compareLists(const std::vector<int>& list1, const std::vector<int>& list2) { if (list1.size() != list2.size()) { return false; } for (size_t i = 0; i < list1.size(); ++i) { if (list1[i] != list2[i]) { return false; } } return true; } int main() { std::vector<int> list1={1, 3, 5, 7}; std::vector<int> list2={1, 3, 5, 7}; std::vector<int> list3={1, 2, 4, 5, 8}; if (compareLists(list1, list2)) { std::cout << "LIST 1 AND LIST 2 ARE EQUIVALENT" << std::endl; } else { std::cout << "LIST 1 AND LIST 2 ARE NOT EQUIVALENT" << std::endl; } if (compareLists(list1, list3)) { std::cout << "LIST 1 AND LIST 3 ARE EQUIVALENT" << std::endl; } else { std::cout << "LIST 1 AND LIST 3 ARE NOT EQUIVALENT" << std::endl; }
OUTPUT: