gpt4 book ai didi

c++ - 如何将 unsigned char[] 转换为 std::vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:02 26 4
gpt4 key购买 nike

我正在尝试将其传递给我的项目的另一部分,该部分要求它是一个 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());
}

我得到了错误

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

最佳答案

return (vch, vch + size());

这使用逗号运算符 - 长话短说,写

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

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

相反。 (后者在语义上是等效的,但在可读性方面更可取)或者使用 C++11:

return {vch, vch + size()};

这确实有效,因为带指针的花括号初始化列表无法转换为 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.

现在,是否有可行的初始化列表构造函数? [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.

显然没有从 unsigned char* 隐式转换至 unsigned char ,因此选择了迭代器对构造函数模板。 Demo .

关于c++ - 如何将 unsigned char[] 转换为 std::vector<unsigned char>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27951537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com