将 char 缓冲区附加到矢量;在STL中

发布于 2024-08-03 20:02:38 字数 98 浏览 2 评论 0原文

将 C 缓冲区 (char *) 的内容附加到 std::vector 末尾的正确(且有效)方法是什么?

What is the correct (and efficient) way of attaching the contents of C buffer (char *) to the end of std::vector<char>?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

救赎№ 2024-08-10 20:02:38

当您有可用的 vector 时,您可能最好调用 vector::insert 方法:

std::vector<char> vec;

const char* values="values";
const char* end = values + strlen( values );

vec.insert( vec.end(), values, end );

最好将其委托给向量使用 back_inserter 因为向量可以决定其最终大小。 back_inserter 只会 push_back,可能会导致更多的重新分配。

When you have a vector<char> available, you're probably best calling the vector<char>::insert method:

std::vector<char> vec;

const char* values="values";
const char* end = values + strlen( values );

vec.insert( vec.end(), values, end );

Delegating it to the vector is to be preferred to using a back_inserter because the vector can then decide upon its final size. The back_inserter will only push_back, possibly causing more reallocations.

土豪我们做朋友吧 2024-08-10 20:02:38

我认为正确的方法是

vec.insert(vec.end(),buf,buf+length);

std::copy(buf,buf+length,std::back_inserter(vec));

编辑:我重新排序了两个例子,所以这并不是评论者错了,这只是我的问题;-)

I think the proper way would be to

vec.insert(vec.end(),buf,buf+length);

or

std::copy(buf,buf+length,std::back_inserter(vec));

Edit: I reordered two examples, so it's not that commenters are wrong, it's just me ;-)

无人接听 2024-08-10 20:02:38

我没有编译过,但应该是这样的:

const char string1[] = "a string";
std::vector<char> vData;
vData.insert(vData.end(), string1, string1+strlen(string1));

I haven't compiled it, but it should be something like:

const char string1[] = "a string";
std::vector<char> vData;
vData.insert(vData.end(), string1, string1+strlen(string1));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文