简体   繁体   中英

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*>'
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 .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM