gpt4 book ai didi

c++ - STL vector 数据提取

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:30 28 4
gpt4 key购买 nike

我有一个 std::vector<char>大小约为 1500 .但是当我尝试使用 vector::data将数据提取到字符串中,这是行不通的。

std::vector<char> testVector;
//insert data to test vector
std::string temp = testVector.data();

当我打印 temp 时在此之后,它只打印 DATA .当我减小 data 的大小时在 vector到 100-200,它正常工作并且符合预期。但是当尺寸增加时,它会停止工作。我尝试使用 string::reserve , 仍然没有。

我错过了什么?

最佳答案

分配 char*到一个字符串需要一个以 null 结尾的字符串。

复制一个(非空终止)vector<char>进入 string ,使用:

std::string temp(testVector.data(), testVector.size());

或(这更符合惯用语,因为它可以与任何容器一起使用):

std::string temp(testVector.begin(), testVector.end());

关于c++ - STL vector 数据提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20244926/

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