Does C++ or Boost has a function that compares two blocks of memory just like the C's memcmp?
I tried Google but I only got the "memcmp" function.
If you want a function which can handle both pointers and STL iterators take a look at std::equal
in <algorithm>
.
I'd consider std::equal
to be the C++ way of doing std::memcmp
(which is indeed still C++, but std::memcmp
doesn't handle iterator objects).
#include <iostream>
#include <vector>
#include <algorithm>
int
main (int argc, char *argv[])
{
int a1[] = {1,2,3,4};
int a2[] = {1,9,3,5};
int * p1 = new int[4];
std::vector<int> vec (a2, a2+4);
*(p1++) = 1; *(p1++) = 2;
*(p1++) = 3; *(p1++) = 4;
p1 -= 4;
if (std::equal (a1, a1+4, p1)) {
std::cout << "memory of p1 == memory of a1\n";
}
if (std::equal (vec.begin (), vec.end (), p1) == false) {
std::cout << "memory of p1 != memory of vec\n";
}
}
output
memory of p1 == memory of a1
memory of p1 != memory of vec
You can use memcmp
in C++ as well. It is native in C++ too.
All that you need to do is, include <cstring>
and then use fully-qualified name std::memcmp
instead of memcmp
. It is because it is in std
namespace, like every other standard library functions and classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With