Is there a native C ++ alternative for C "memcmp"?

Does C ++ or Boost have a function that compares two memory blocks in the same way as C memcmp?

I tried Google, but I only got the "memcmp" function.

+6
source share
5 answers

You can use memcmp in C ++. It is also native in C ++.

All you have to do is include <cstring> and then use the fully qualified name std::memcmp instead of memcmp . This is because it is in the std , like all other standard library functions and classes.

+12
source

If you need a function that can handle both pointers and STL iterators, look at std::equal in <algorithm> .

I believe that std::equal is C ++ - a way to execute std::memcmp (which is really C ++, but std::memcmp does not 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"; } } 

Exit

 memory of p1 == memory of a1 memory of p1 != memory of vec 
+22
source

Use memcmp. This is a completely legitimate C ++ function.

+1
source

memcmp is part of the C ++ standard library (by inclusion).

+1
source

memcmp is part of the C ++ standard library and is available in <cstring> . Since your requirement is to compare 2 memory blocks (dealing with raw memory), you should use memcmp or other functions in the library.

If you don't want to deal with memory, use C ++ containers for abstract memory management. Then you will deal with objects!

+1
source

Source: https://habr.com/ru/post/903654/


All Articles