HOWTO · C++
How to Compare Arrays in C++
Compare C++ arrays and ranges safely with loops, standard algorithms, byte comparison, and std::vector equality.
On this page
Choose a comparison method based on the input and the result you need. For equal-length fixed-size arrays, a loop or std::equal can return a Boolean. For byte sequences, std::memcmp compares object representations. For vectors, std::vector’s operator== compares sizes and values. When you need the first differing position, use std::mismatch after checking the range lengths.
The examples below are complete C++ programs intended to be compiled individually. The supplied runtime results report successful execution for all six examples. Raw array parameters decay to pointers: a function receiving them cannot determine their lengths. Pass the lengths explicitly and ensure each pointer refers to a range at least that long.
Compare fixed-size arrays with a loop
A loop makes the comparison rule explicit: inspect corresponding elements and return false as soon as a pair differs. If every pair matches, return true. The caller supplies both lengths, so check them before indexing; this example handles different lengths without reading either range.
#include <cstddef>
#include <iostream>
bool equalArrays(const int* left, std::size_t leftSize,
const int* right, std::size_t rightSize) {
if (leftSize != rightSize) return false;
for (std::size_t i = 0; i < leftSize; ++i) {
if (left[i] != right[i]) return false;
}
return true;
}
int main() {
const int first[] = {2, 4, 6, 8};
const int same[] = {2, 4, 6, 8};
const int different[] = {2, 4, 6, 9};
constexpr std::size_t count = sizeof(first) / sizeof(first[0]);
std::cout << std::boolalpha
<< equalArrays(first, count, same, count) << '\n'
<< equalArrays(first, count, different, count) << '\n';
}
true
false
The first call compares every corresponding value and returns true; the second stops at the final pair and returns false. This element-wise approach works when != has the meaning you want for the element type. It does not compare array sizes automatically, so pass the actual sizes rather than assuming two pointers refer to equally sized arrays.
Write a reusable comparison function
A template can reuse the loop for types that support inequality comparison. As with the integer version, the function takes lengths explicitly and checks them before reading elements. The example is separate and can be compiled on its own.
#include <cstddef>
#include <iostream>
#include <string>
template <typename T>
bool equalRanges(const T* left, std::size_t leftSize,
const T* right, std::size_t rightSize) {
if (leftSize != rightSize) return false;
for (std::size_t i = 0; i < leftSize; ++i) {
if (left[i] != right[i]) return false;
}
return true;
}
int main() {
const std::string namesA[] = {"Ada", "Lin"};
const std::string namesB[] = {"Ada", "Lin"};
std::cout << std::boolalpha
<< equalRanges(namesA, 2, namesB, 2) << '\n';
}
true
The template parameter T is deduced from the elements. The function requires T to support !=; it does not require a particular container. Keep the pointer and length paired, and ensure the named range is alive and large enough for the supplied length. For standard containers, prefer their iterators or a container-aware operation when that makes the bounds clearer.
Compare ranges with std::equal
std::equal from <algorithm> compares corresponding elements and returns a Boolean. The three-iterator overload takes the first range’s begin and end plus the second range’s begin. Before calling it, compare lengths: the second range must contain at least as many elements as the first. Checking equality of lengths gives whole-range equality and prevents reading beyond the second range.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
const std::vector<int> left{3, 1, 4};
const std::vector<int> same{3, 1, 4};
const std::vector<int> longer{3, 1, 4, 1};
const bool firstEqual = left.size() == same.size() &&
std::equal(left.begin(), left.end(), same.begin());
const bool secondEqual = left.size() == longer.size() &&
std::equal(left.begin(), left.end(), longer.begin());
std::cout << std::boolalpha << firstEqual << '\n' << secondEqual << '\n';
}
true
false
The size checks are part of the comparison, not an optional optimization. std::equal compares in order; elements at the same position must compare equal. Use this algorithm with iterator ranges whose lifetimes and bounds are valid. The four-iterator overload can express both ends directly in language versions that provide it, but the size-check pattern above avoids relying on that overload.
Compare bytes with std::memcmp
std::memcmp in <cstring> compares a specified number of bytes. It returns zero when those bytes match and a nonzero value when they differ; the sign can indicate bytewise ordering, but do not depend on an exact nonzero value. Supply valid pointers to at least the requested byte count, and calculate the count in bytes, not elements.
#include <cstring>
#include <iostream>
int main() {
const unsigned char left[] = {0x10, 0x20, 0x30};
const unsigned char same[] = {0x10, 0x20, 0x30};
const unsigned char different[] = {0x10, 0x20, 0x31};
constexpr std::size_t byteCount = sizeof(left);
std::cout << (std::memcmp(left, same, byteCount) == 0) << '\n'
<< (std::memcmp(left, different, byteCount) == 0) << '\n';
}
1
0
This example uses byte arrays, for which bytewise comparison directly answers whether the listed bytes match. For general objects, equal values do not necessarily have identical object representations: padding bytes or multiple representations of a value can make std::memcmp unsuitable. Prefer element equality for ordinary values, and use byte comparison only when the data format makes representation equality the intended rule. A zero byte count compares no bytes; callers still need valid range handling appropriate to their program.
Compare vectors with std::vector::operator==
For vectors, use == when you need whole-vector value equality. It checks that the sizes match and that corresponding elements compare equal, so a separate size check is unnecessary. Order matters: vectors with the same values in a different order are not equal.
#include <iostream>
#include <vector>
int main() {
const std::vector<int> first{5, 8, 13};
const std::vector<int> same{5, 8, 13};
const std::vector<int> reordered{8, 5, 13};
const std::vector<int> shorter{5, 8};
std::cout << std::boolalpha
<< (first == same) << '\n'
<< (first == reordered) << '\n'
<< (first == shorter) << '\n';
}
true
false
false
This is the most direct choice when both inputs are std::vector and a Boolean answer is enough. The contained type must support equality comparison. If your task considers order irrelevant, define that rule explicitly and use an approach suited to it; ordinary vector equality intentionally compares positions.
Find the first difference with std::mismatch
Use std::mismatch when you need the first differing pair rather than only true or false. Its three-iterator overload advances through the first range and the second range, so first compare their lengths to ensure both ranges end together. The returned first iterator identifies the first range’s differing element; if it equals the first range’s end, every compared pair matched.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
const std::vector<int> left{7, 8, 9, 10};
const std::vector<int> right{7, 8, 0, 10};
if (left.size() != right.size()) {
std::cout << "Different lengths\n";
return 0;
}
const auto result = std::mismatch(left.begin(), left.end(), right.begin());
if (result.first == left.end()) {
std::cout << "Equal\n";
} else {
const auto index = std::distance(left.begin(), result.first);
std::cout << "First mismatch at zero-based index " << index << '\n';
}
}
First mismatch at zero-based index 2
std::distance gives a zero-based offset here. If presenting a human-facing one-based position instead, label it as such and add one to the offset. Comparing lengths first also makes the end condition meaningful for whole-range equality and keeps the second iterator within its range.
Choose a comparison method
Use a loop when you want explicit control over element-by-element checks or need custom logic. Use std::equal for a Boolean comparison of iterator ranges, after confirming compatible lengths for its three-iterator overload. For std::vector, operator== is the concise whole-container check. Choose std::mismatch when the location of the first difference matters.
Reserve std::memcmp for byte sequences whose representation is the data being compared; it is not a general replacement for value equality. In every pointer-based approach, pair pointers with correct lengths. Prefer container sizes and iterator ranges when available, and make sure the second range is long enough before using an algorithm that advances through it.