简体   繁体   English

两种重新初始化向量的方法有什么区别吗?

[英]is there any difference between two methods that re-initializing vector?

I use two methods when I re-initialize vector重新初始化向量时我使用两种方法

vector<int> vec(1000, 1);

//first
vec.assign(1000, 2);

//second
vec = vector<int>(1000, 3);

I think these two methods are produce same result, but I found that the second method takes up less memory.我认为这两种方法产生相同的结果,但我发现第二种方法占用更少的内存。

Is there something difference between these two method??这两种方法有什么区别吗??

The difference is how the internal memory of the std::vector is handled.不同之处在于std::vector的内部存储器是如何处理的。

With

std::vector<int> vec(1000, 1);

You created a new std::vector called vec .您创建了一个名为vec的新std::vector It allocates memory to hold 1000 int s and initializes their values to 1 .它分配内存来容纳 1000 个int并将它们的值初始化为1

In the first method:在第一种方法中:

vec.assign(1000, 2);

You then tell vec to reuse that allocated memory, where the 1000 int s live.然后,您告诉vec重用分配的内存,其中 1000 个int存在。 They are simply overwritten by values of 2 .它们只是被2的值覆盖。

In the second method:在第二种方法中:

std::vec = std::vector<int>(1000, 3);

You actually do two things - you create a new std::vector which allocates memory for 1000 int s and initializes their values to 3 .您实际上做了两件事 - 创建一个新的std::vector ,它为 1000 个int分配内存并将它们的值初始化为3 Then this new vector is move assigned to vec , which in turn will throw away its memory of 2 s and take the internal memory of the anonymous unnamed vector with its 3 s, because its a so-called rvalue .然后这个新向量被移动分配vec ,它反过来会丢弃它的2秒内存,并用它的3秒占用匿名未命名向量的内部内存,因为它是一个所谓的rvalue

The overall memory consumption should be the same in the end, although when using the 2nd method, for a moment you have 2 allocated memory regions of 1000 int s each, alive at the same time.总体内存消耗最终应该是相同的,尽管在使用第二种方法时,有一段时间您有 2 个分配的内存区域,每个区域 1000 个int s,同时处于活动状态。

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

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