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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4758257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:23:28  来源:igfitidea点击:

How to copy a range of data from char array into a vector?

c++stdvector

提问by Newbie

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?

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

回答by sbi

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

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

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

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

当然,还有一个assign(),它可能更接近你想要做的:

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:

但是,阅读您的问题时,我想知道为什么您会首先读入 C 数组只是为了将其内容复制到向量中,而您可以立即读入向量。Astd::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 mustmake 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 Behaviorwhen you fail on this.

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