Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char * to vector<unsigned char> Initalisation

I understand that using vector is a good way to store binary data when using C++ and the STL. However for my unit tests I'd like to initalise the vector using a const char* C string variable.

I'm attempting to use a variant of the code found here - Converting (void*) to std::vector<unsigned char> - to do this:

const char* testdata = "the quick brown fox jumps over the lazy dog.";

unsigned char* buffer = (unsigned char*)testdata;
typedef vector<unsigned char> bufferType;

bufferType::size_type size = strlen((const char*)buffer);
bufferType vec(buffer, size);

However the VC++ compiler is not happy with the line initialising the vector, stating:

error C2664: 'std::vector<_Ty>::vector(unsigned int,const _Ty &)' : cannot convert parameter 1 from 'char *' to 'unsigned int'

I appreciate the extreme n00bity of this question and am fully prepared for much criticism on the code above :)

Thanks in advance, Chris

like image 339
Mr Chris Avatar asked Mar 21 '12 06:03

Mr Chris


2 Answers

It should be

bufferType vec(buffer, buffer + size);

not

bufferType vec(buffer, size);
like image 194
Luchian Grigore Avatar answered Sep 22 '22 23:09

Luchian Grigore


std::transform is useful for just this sort of problem. You can use it to "transform" one piece of data at a time. See documentation here:

http://www.cplusplus.com/reference/algorithm/transform/

The following code works in VS2010. (I created a std::string from your const char* array, but you could probably avoid that if you really wanted to.)

#include <algorithm>
#include <vector>

int main(int, char*[])
{
  // Initial test data
  const char* testdata = "the quick brown fox jumps over the lazy dog.";

  // Transform from 'const char*' to 'vector<unsigned char>'
  std::string input(testdata);
  std::vector<unsigned char> output(input.length());
  std::transform(input.begin(), input.end(), output.begin(),
    [](char c)
    {
      return static_cast<unsigned char>(c);
    });

  // Use the transformed data in 'output'...


  return 0;
}
like image 44
aldo Avatar answered Sep 24 '22 23:09

aldo