gpt4 book ai didi

c++ - const char * 对 vector 的初始化

转载 作者:可可西里 更新时间:2023-11-01 16:29:21 57 4
gpt4 key购买 nike

我知道在使用 C++ 和 STL 时,使用 vector 是存储二进制数据的好方法。但是,对于我的单元测试,我想使用 const char* C 字符串变量来初始化 vector 。

我正在尝试使用此处找到的代码变体 - Converting (void*) to std::vector<unsigned char> - 这样做:

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);

但是 VC++ 编译器对初始化 vector 的行不满意,指出:

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

我很欣赏这个问题的极端 n00bity,并且已经做好充分准备接受对上面代码的大量批评:)

提前致谢,克里斯

最佳答案

应该是

bufferType vec(buffer, buffer + size);

不是

bufferType vec(buffer, size);

关于c++ - const char * 对 vector<unsigned char> 的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9799598/

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