Minato
Minato

Reputation: 89

How to convert unsigned char[] to std::vector<unsigned char>

I am trying to pass this to another part of my project that requires it be a vector

unsigned char vch[65];

unsigned int size() const { return GetLen(vch[0]); }
const unsigned char* begin() const { return vch; }
const unsigned char* end() const { return vch + size(); 


std::vector<unsigned char> Raw() const
{
        return (vch, vch + size());
}

I get the error

 could not convert '(const unsigned char*)(&((const CPubKey*)this)-
CPubKey::vch)' from 'const unsigned char*' to 'std::vector<unsigned char*>'

Upvotes: 5

Views: 15666

Answers (2)

Columbo
Columbo

Reputation: 60999

return (vch, vch + size());

This uses the comma operator - long story short, write

return std::vector<unsigned char>(vch, vch + size());

or

std::vector<unsigned char> vec(vch, vch + size())
return vec;

instead. (The latter is semantically equivalent but preferable in terms of readability) Or with C++11:

return {vch, vch + size()};

This does work because a braced-init-list with pointers cannot be converted to initializer_list<unsigned char>. [over.match.list]/1:

When objects of non-aggregate class type T are list-initialized such that 8.5.4 specifies that overload resolution is performed according to the rules in this section, overload resolution selects the constructor in two phases:

  • Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T [..]

  • If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

Now, is there a viable initializer-list constructor? [over.ics.list]:

  1. Otherwise, if the parameter type is std::initializer_list<X> and all the elements of the initializer list can be implicitly converted to X, [..]

 10. In all cases other than those enumerated above, no conversion is possible.

There is clearly no implicit conversion from unsigned char* to unsigned char, so the iterator-pair constructor template is chosen. Demo.

Upvotes: 12

SHR
SHR

Reputation: 8333

It is may not answering directly to the answer.

But the question is why to use a vector when you can use std::string, or std::basic_string<unsigned char> instead of std::vector, like this:

unsigned char a[]="1234";
std::basic_string<unsigned char> v=a;

Upvotes: 0

Related Questions