Open In App

How to Compare Two Lists in C++ STL?

Last Updated : 21 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, lists are containers provided by the STL library of C++, which allows us to store elements of the same data type in non-contiguous memory locations. Comparing two lists is a very common operation while using lists. In this article, we will learn how to compare two lists in C++.

Example:

Input: 
list1 = {10, 20, 30, 40, 50}
list2 = {10, 20, 30, 40, 50}

Output:
Both the lists are equal.

Comparing Two Lists in C++

To compare two std::list in C++, we can simply use the equality operator (==) that compares all the corresponding elements in the two lists from start to end and if all pairs of elements in both lists are equal it returns true otherwise false.

Syntax to Compare Two Lists in C++

list1 == list2

Here,

  • list1 and list2 are the name of the two list containers.
  • Return value: Boolean true or false.

C++ Program to Compare Two Lists

The below program demonstrates how to compare two std::list containers in C++.

C++
// C++ program to compare two lists

#include <iostream>
#include <list>
using namespace std;

int main()
{
    // Initializing two lists of integers
    list<int> list1 = { 10, 20, 30, 40, 50 };
    list<int> list2 = { 10, 20, 30, 40, 50 };

    // Comparing the two lists
    bool equal = (list1 == list2);
    if (equal == true) {
        cout << "Both the lists are equal." << endl;
    }
    else {
        cout << "Both the lists are not equal." << endl;
    }

    return 0;
}

Output
Both the lists are equal.

Time Complexity: O(N), where N is the size of two lists.
Auxiliary Space: O(1), as no extra space is used.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads