简体   繁体   English

动态数组的时间复杂度和增长策略

[英]Time complexity and growth strategy of dynamic arrays

I was reading in More Exceptional C++ by Herb Sutter about growth strategy to be chosen when implementing a string. 我在Herb Sutter的《 More Exceptional C ++》中读到关于实现字符串时要选择的增长策略的信息。 He lists the following: 他列出了以下内容:

1) Exact growth. 1)确切的增长。 In this strategy, the new buffer is made exactly as large as required by the current operation 在此策略中,新缓冲区的大小应与当前操作所需的大小完全相同

Advantage: no wasted space. 优势:不浪费空间。

Disadvantage: poor performance. 缺点:性能差。 This strategy requires O(N) allocations and an average of O(N) copy operations per char, but with a high constant factor in the worst case... 该策略需要O(N)分配和每个字符平均O(N)个复制操作,但在最坏的情况下具有较高的恒定因子...

2) Fixed-increment growth. 2)固定增量增长。 The new buffer should be a fixed amount larger than the current buffer 新缓冲区应比当前缓冲区大一个固定数量

Advantage: little wasted space. 优点:空间浪费少。 The amount of unused space in the buffer is bounded by the increment size, and does not vary with the length of the string. 缓冲区中未使用的空间量由增量大小限制,并且不会随字符串的长度而变化。

Disadvantage: moderate performance. 缺点:性能中等。 This strategy requires both O(N) allocations and an average of O(N) copy operations per char. 此策略需要O(N)分配和每个字符平均O(N)个复制操作。 That is, both the number of allocations and the average number of times a given char is copied vary linearly with the length of the string. 也就是说,分配数和复制给定char的平均次数均随字符串的长度线性变化。 However, control of the constant factor is in the hands of the String implementer. 但是,常量因子的控制权在String实现者的手中。

note: characters are added to the string 1 by 1 注意:字符将被一一添加到字符串中

Question 1 : How does the constant factor controlled in both? 问题1 :两者中的常数如何控制? I din't Understand Herb's point here 我在这里不懂Herb的观点

Question 2 : How will the Fixed increment be O(N), wouldn't depend on what the fixed size used is, if say its 100 chars, after the first resize, the next 99 insertions would be O(1), so why O(N) is considered? 问题2 :固定增量将如何为O(N),而不取决于所使用的固定大小,如果说是100个字符,则在第一次调整大小后,接下来的99个插入将是O(1),为什么?是否考虑O(N)?

  1. The string implementer gets to choose how big the fixed-size increment f is. 字符串实现者可以选择固定大小的增量f有多大。 So he has control over the constant factor in 2), but not in 1). 因此他可以控制2)中的常数,但不能控制1)。 Note that there is no claim of control over the constant factor in 1). 请注意,没有声称可以控制1)中的常数因子。

  2. The cost per char would be O(N/ f ). 每个字符的成本为O(N / f )。 I believe what Herb means is that f is fixed by the implementation, and hence is essentially a constant factor in the big-oh notation (ie it's dropped). 我相信Herb的意思是f由实现固定,因此本质上是big-oh表示法(即,它被删除)中的常数。 However, the larger the f the smaller the big-oh constant factor is, and hence better performance (at the cost of more wasted space). 但是, f越大,大常数常数越小,因此性能越好(以浪费更多空间为代价)。 So the implementer has to weigh those two factors when choosing f . 因此,实施者在选择f时必须权衡这两个因素。

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

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