Stringstream 到 Vector<char>抛出 std::bad_alloc [英] Stringstream to Vector&lt;char&gt; throws std::bad_alloc

查看:40
本文介绍了Stringstream 到 Vector<char>抛出 std::bad_alloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Boost 属性树进行了一些修改,结果发现了这个示例.我需要将最终结果转换为向量,所以我只是在

I was tinkering with Boost Property Tree a bit, and I came across this example. I needed to convert the final result to vector, so I just added one more line after

write_json(ss, root);

像这样:

std::vector<char> testVec(std::begin(ss.str()), std::end(ss.str()));

我也试过这个:

std::string someString = ss.str()
char* someArray = (char*)someString.c_str();
std::vector<char> someVec(someArray, someArray+sizeof(someArray));

在这两种情况下,我都收到此错误:

In both the cases, I am getting this error:

terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc

任何提示我做错了什么?这不是属性树的问题,我收集.这是字符串到向量转换的问题.我想这是有道理的,因为向量应该只是一维的,但我不知道如何将该字符串转换为向量并再次返回.

Any hints what I am doing wrong? It is not a problem of property tree, I gather. It is a problem of string to vector conversion. I guess this makes sense, because vectors are only supposed to be one dimensional, but I have no clue how to convert that string to vector and get it back again.

推荐答案

这失败了:

std::vector<char> testVec(std::begin(ss.str()), std::end(ss.str())); 

因为 std::begin()std::end() 没有关联到同一个 std::string 实例.ss.str() 返回一个新的 std::string 实例每次都不会返回 std::string& 给某个内部成员.

because the std::begin() and std::end() are not associated with same std::string instance. The ss.str() returns a new std::string instance each time, it does not return a std::string& to some internal member.

这是不正确的:

std::vector<char> someVec(someArray, someArray+sizeof(someArray)); 

因为sizeof(someArray)sizeof(char*).如果 someArray 中的元素少于 sizeof(char*) 元素,将尝试读取不应读取的内存.

because sizeof(someArray) is sizeof(char*). If there is less than sizeof(char*) elements in someArray an attempt will be made to read memory that should not.

一个可能的解决方案:

std::string someString = ss.str();
std::vector<char> someVec(someString.begin(), someString.end());

这篇关于Stringstream 到 Vector<char>抛出 std::bad_alloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆