如何将数组的内容插入向量? [英] How can I insert the content of arrays into a vector?

查看:72
本文介绍了如何将数组的内容插入向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用std::vector编写一些简单的代码,但是我有点挣扎.

I need to write some simple code with std::vectors and I am struggling a bit.

我有一个char[]缓冲区,里面装有来自另一个程序的回调数据.我需要将此数据附加到向量的末尾-整个缓冲区.

I have a char[] buffer that is filled with callback data from another program. I need to append this data to the end of a vector - the whole buffer.

std::vector<char> vector; 

// data comes from another program
void callback(char buffer[], size_t size)
{
    // copy buffer to the end of vector here   
}

最后,向量应该包含来自缓冲区的连续数据.

At the end the vector is supposed to contain continuous data from the buffer.

有没有一种有效的方法,而无需通过循环逐个元素地插入?

Is there an effective way to do this without inserting element by element with a loop?

for (size_t i = 0; i < size; ++i)
    vector.push_back(buffer[i]);

推荐答案

假设您知道大小,则可以插入一个范围:

Assuming you know the size, you can insert a range:

vector.insert(vector.end(), buffer, buffer + size);

对于这种事情,还有一种更通用的算法:

There's also a more generic algorithm for this sort of thing:

#include <iterator>
#include <algorithm>

std::copy(buffer, buffer + size, std::back_inserter(vector));

这篇关于如何将数组的内容插入向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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