Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a native C++ alternative to the C's "memcmp"?

Tags:

c++

boost

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.

like image 808
malhobayyeb Avatar asked Dec 13 '11 06:12

malhobayyeb


2 Answers

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
like image 139
Filip Roséen - refp Avatar answered Sep 18 '22 06:09

Filip Roséen - refp


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.

like image 34
Nawaz Avatar answered Sep 21 '22 06:09

Nawaz