如何将字符数组中的一系列数据复制到向量中?
我已将文件内容读入字符数组,然后将其中的一些数据读入向量。 如何将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以使用
insert()
成员函数向向量添加某些内容:当然,还有一个
assign()
,这可能更接近您想要做的事情:但是,在阅读您的问题时,我想知道为什么您首先读入 C 数组只是为了将其内容复制到向量中,而您可以立即读入向量。
std::vector<>
需要将其数据保存在一个连续的内存块中,并且您可以通过获取其第一个元素的地址来访问该块。只需确保向量中有足够的空间即可:除了
&vec[0]
,您还可以通过&*vec.begin()
获取第一个元素的地址代码>.但请注意,无论使用哪种方法,您都绝对必须确保向量中至少有一个元素。这两种方法都不需要检查它(尽管您的实现可能会在调试版本中这样做),并且当您失败时,这两种方法都会调用可怕的未定义行为。Appending something to a vector can be done using the
insert()
member function:Of course, there's also an
assign()
, which is probably closer to what you want to do: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: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.