Different behaviour from similar methods in Vec and VecDeque

Hi!

I have a program which I tried to implement with VecDeque and Vec. According to my understanding and from what I read in the docs, pop_back(VecDeque) is similar to pop(Vec) and push_back(VecDeque) is similar to push(Vec).

But in this program, It passes the test with Vec and fails the test with VecDeque.

I have went over the program 100 times and read the docs and I just can't figure this out.

Here is the Playground Link.

The two versions of the program are basically methods on VecStack and VecDequeStack.

Hi, your problem comes from capacity.
If you check the capacity of both collections when they are created, you'll notice they aren't the same, making your program fail at some point.

This is documented in both collections (emphasis mine):

Creates an empty VecDeque with space for at least capacity elements.

I added a field to both and it works. playground

I tried to give them the same capacity but it doesn't seem to work for all values so I don't think you can use it.

3 Likes

Thank you for pointing out the difference. I had just assumed for no reason with_capacity must be doing the exact same thing.

I checked VecDeque docs but they don't say why is it this way?

The implementation of wrapping indices in VecDeque requires that the capacity is always a power of 2.

(This also means that VecDeque, unlike all the other standard collections, requires a heap allocation even when it is empty.)

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.