如何将字符数组中的一系列数据复制到向量中?

发布于 2024-10-13 08:29:51 字数 340 浏览 4 评论 0原文

我已将文件内容读入字符数组,然后将其中的一些数据读入向量。 如何将 char 数组的范围复制到向量中?矢量和字符数组都是相同的类型(无符号字符)。

当前的代码是这样的:

int p = 0;

for(...){
    short len = (arr[p+1] << 8) | arr[p+0];
    p+=2;
    ...
    for(...len...){
        vec.push_back(arr[p]);
        p++;
    }
}

我想通过使用 push_back 删除循环来改进这一点,如何?

I've read file contents into a char array, and then read some data of it into a vector.
How can i copy a range of the char array into the vector? both vector and char array is the same type (unsigned char).

Current code goes something like this:

int p = 0;

for(...){
    short len = (arr[p+1] << 8) | arr[p+0];
    p+=2;
    ...
    for(...len...){
        vec.push_back(arr[p]);
        p++;
    }
}

I would like to improve this by dropping the loop with push_back, How?

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

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

发布评论

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

评论(1

罪歌 2024-10-20 08:29:51

可以使用 insert() 成员函数向向量添加某些内容:

vec.insert(vec.end(), arr, arr+len);

当然,还有一个 assign(),这可能更接近您想要做的事情:

vec.assign(arr, arr+len);

但是,在阅读您的问题时,我想知道为什么您首先读入 C 数组只是为了将其内容复制到向量中,而您可以立即读入向量。 std::vector<> 需要将其数据保存在一个连续的内存块中,并且您可以通过获取其第一个元素的地址来访问该块。只需确保向量中有足够的空间即可:

std::size_t my_read(char* buffer, std::size_t buffer_size);

vec.resize( appropriate_length );
vec.resize( my_read_func(&vec[0], vec.size()) );

除了 &vec[0],您还可以通过 &*vec.begin() 获取第一个元素的地址代码>.但请注意,无论使用哪种方法,您都绝对必须确保向量中至少有一个元素。这两种方法都不需要检查它(尽管您的实现可能会在调试版本中这样做),并且当您失败时,这两种方法都会调用可怕的未定义行为

Appending something to a vector can be done using the insert() member function:

vec.insert(vec.end(), arr, arr+len);

Of course, there's also an assign(), which is probably closer to what you want to do:

vec.assign(arr, arr+len);

However, reading your question I wondered why you would first read into a C array just to copy its content into a vector, when you could read into a vector right away. A std::vector<> is required to keep its data in one contiguous block of memory, and you can access this block by taking the address of its first element. Just make sure you have enough room in the vector:

std::size_t my_read(char* buffer, std::size_t buffer_size);

vec.resize( appropriate_length );
vec.resize( my_read_func(&vec[0], vec.size()) );

Instead of &vec[0] you could also get the address of the first element by &*vec.begin(). However, note that with either method you absolutely must make sure there's at least one element in the vector. None of the two methods are required to check for it (although your implementation might do so for debug builds), and both will invoke the dreaded Undefined Behavior when you fail on this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文