Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing an std::array to a traditional array C++

Tags:

c++

arrays

c++11

I am trying to perform a comparison of elements in:

std::vector<std::array<uint8_t, 6> > _targets =
{
  { 0x00, 0x00, 0x00, 0x00, 0x00, 0x11 }
  { 0x00, 0x00, 0x00, 0x00, 0x00, 0x22 }
};

to a traditional array:

 uint8_t _traditional[6] =  { 0x00, 0x00, 0x00, 0x00, 0x00, 0x33 }

as:

  for (auto target : _targets) 
  {

     if (! memcmp(target, _traditional, 6)) {
        known = 1;
     } 
  }

and am receiving a data conversion error:

error: cannot convert 'std::array<unsigned char, 6u>' to 'const void*' for argument '1' to 'int memcmp(const 
void*, const void*, size_t)

What is the propert byte wise comparison operation I can perform to accomplish equality evaluation?

like image 378
Rice Avatar asked Aug 09 '18 23:08

Rice


People also ask

What is the difference between std :: array and array?

std::array is just a class version of the classic C array. That means its size is fixed at compile time and it will be allocated as a single chunk (e.g. taking space on the stack). The advantage it has is slightly better performance because there is no indirection between the object and the arrayed data.

Is std :: array slower than C array?

It will provide a value like semantics equally to the other C++ containers. A std::array should have same runtime performance as a c-style array.

Should I use std array C++?

What are the advantages of using std::array over usual ones? It has friendly value semantics, so that it can be passed to or returned from functions by value. Its interface makes it more convenient to find the size, and use with STL-style iterator-based algorithms.

What are the benefits of using the std :: array?

std::array provides many benefits over built-in arrays, such as preventing automatic decay into a pointer, maintaining the array size, providing bounds checking, and allowing the use of C++ container operations.


1 Answers

You can use the data() member of array to get a pointer to the contained array:

if (! memcmp(target.data(), _traditional, 6))

The alternative of using &target[0] will work in this case (where you're storing a uint8_t) but won't work if you store a class that overloads the unary & (address) operator. But you could use std::addressof(target[0]) which will work even in the presence of an overloaded address operator.

like image 52
CoralK Avatar answered Sep 28 '22 09:09

CoralK