简体   繁体   English

替换一堆std :: vector条目

[英]Replace a bunch of std::vector entries

I have a std::vector. 我有一个std :: vector。 I assign this vector like 我将这个向量分配为

vec.assign(20000, 0);

Now I have an additional array, which I want to insert into the vector. 现在,我有一个附加数组,我想将其插入向量中。 But NOT just like insert, more replace elements in the vector. 但是不仅仅是插入,还需要替换向量中的更多元素。

uint8_t a[] = {1,2,3,4,5,6,7,8};

Move that array into the vector on position x - x+8 without allocating new memory. 将该数组移到位置x-x + 8的向量中,而无需分配新的内存。

What I tried and works is of course 我尝试和工作的当然是

vec.insert(start, a, a+8);

But there I am allocating new memory and the size of the vector changes, which is not supposed to happen. 但是我在那里分配了新的内存,向量的大小也发生了变化,这是不应该发生的。 Yes, I could delete, the entries, which are too much, but there's still the problem, that I am allocating more memory. 是的,我可以删除太多的条目,但是仍然存在我分配更多内存的问题。 Isn't there a possibility, to just replace the array with the contents of the vector? 仅用向量的内容替换数组,有没有可能? Smth like that: 像这样:

vec.replace(start, a, a+8);

I wanted to avoid replacing each element, cause I am afraid that could take too long. 我想避免替换每个元素,因为我担心这可能会花费太长时间。

What do you think? 你怎么看? Is there a way to do that? 有没有办法做到这一点? Have you had that problem before, too? 您以前也遇到过这个问题吗? How did you fix it? 你怎么修好它的?

Simple 简单

#include <algorithm>

std::copy(a, a + 8, vec.begin());

Copies elements from a upto a + 8 and replaces the elements starting at vec.begin() . 从副本元件a高达a + 8 ,并取代在开始的元素vec.begin()

I think you are wrong to worry about efficiency. 我认为担心效率是错误的。 The solution above does replace each element, and would likely be no more nor no less efficient than if you wrote the replacement code yourself. 上面的解决方案确实替换了每个元素,并且与您自己编写替换代码相比,效率可能更高或更高。 If the code above has any advantage it is clarity , a much overlooked advantage. 如果上面的代码有任何优势,那就是清晰度 ,这是一个被忽略的优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM