Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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*>'
like image 219
Minato Avatar asked Jan 14 '15 20:01

Minato


1 Answers

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.

like image 158
Columbo Avatar answered Oct 17 '22 04:10

Columbo