To check if two vectors have the same items regardless of order in C++, you can sort both vectors and then compare them.
In this example,
vector1
and vector2
.std::sort
algorithm from the algorithm
header.==
operator to check if they are equal.==
operator returns true
if the vectors have the same items regardless of order, otherwise false
.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vector1 = {3, 1, 2};
std::vector<int> vector2 = {1, 2, 3};
std::sort(vector1.begin(), vector1.end());
std::sort(vector2.begin(), vector2.end());
bool are_equal = vector1 == vector2;
std::cout << std::boolalpha << are_equal;
return 0;
}
true
In this example,
vector1
and vector2
.std::sort
algorithm from the algorithm
header.==
operator to check if they are equal.==
operator returns true
if the vectors have the same items regardless of order, otherwise false
.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<char> vector1 = {'b', 'c', 'a'};
std::vector<char> vector2 = {'a', 'b', 'c'};
std::sort(vector1.begin(), vector1.end());
std::sort(vector2.begin(), vector2.end());
bool are_equal = vector1 == vector2;
std::cout << std::boolalpha << are_equal;
return 0;
}
true
In this tutorial, we learned How to check if Two Vectors have Same Items (Regardless of Order) in C++ language with well detailed examples.