转换 c++ std::向量到 std::vector(反之亦然)
有没有一种简单的方法可以将 std::vector
转换为 std::vector
(然后再转换回 >std::vector
,而不必手动转换每个字符串并添加分隔符,例如逗号?
Is there an easy way to convert a std::vector<std::string>
to a std::vector<unsigned char>
(and back again to a std::vector<std::string>
, without having to manually convert each string and add a delimiter, such as a comma?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简短的回答是:不。
向量和字符串的实现方式是作为独立的堆分配数组。因此,您可以将
vector
转换为char**
(由 char 数组组成的锯齿状数组),以及vector
当考虑内部结构时,将其转换为char*
(一个 char 数组)。这将你的问题变成:有没有办法连接数组而不必复制它们?不,不,没有。
The short answer is: no.
The way vectors and strings are implemented are as independant, heap-allocated arrays. Therefore, you could transform
vector<string>
intochar**
(a jagged array of arrays of char), andvector<unsigned char>
intochar*
(an array of char) when thinking about internals. This turns your problem into: is there any way to concatenate arrays without having to copy them?No. No there is not.
如果没有新的 for 循环语法,它会有点笨拙,但你明白了。
It's a little more clumsy without the new for loop syntax, but you get the idea.
Boost Serialization 应该可以让你填充数据结构转换为
unsigned char
序列并再次重构。Boost Serialization should let you stuff a data structure into a sequence of
unsigned char
and reconstitute it again.第一个问题是为什么,以及你想做什么?什么是
std::vector
代表什么,其语义应该是什么转换是?如果你只是想连接,那么最简单的
解决方案类似于:将
char
隐式转换为unsigned char
将处理结果。
如果您需要为每个插入某种分隔符或终止符
源中的字符串,您也可以在循环中执行此操作:
终止符,只需将其附加(
push_back
)在insert
之后;对于一个分隔符,我通常有条件地将其附加在
insert
之前,例如:
但问题是:为什么使用
unsigned char
?大概是因为你是格式化为某些特定协议的缓冲区。是否有一些额外的
需要格式化吗?您的协议中字符串的格式是什么?
(通常,它将是长度 + 数据,或以
'\0'
终止。)该协议是否需要某种调整? (对于 XDR——其中一个
,您需要类似: 。)
使用最广泛的协议 -例如
The first question is why, and what are you trying to do? What does the
std::vector<std::string>
represent, and what should the semantics ofthe conversion be? If you just want to concatenate, then the simplest
solution would be something like:
The implicit conversion of
char
tounsigned char
will take care ofthe reslt.
If you need to insert some sort of separator or terminator for each
string in the source, you can do that in the loop as well: for a
terminator, just append it (
push_back
) after theinsert
; for aseparator, I generally append it conditionally before the
insert
,e.g.:
But the question is: why
unsigned char
? Presumably, because you areformatting into a buffer for some specific protocol. Is some additional
formatting required? What is the format of a string in your protocol?
(Typically, it will be either length + data, or
'\0'
terminated.)Does the protocol require some sort of alignment? (For XDR—one of
the most widely used protocols—, you'd need something like:
, for example.)