Difference between Std::list, Std::vector and Std:array

Asked

Viewed 2,100 times

10

All are containers used for data guards in a sequential manner, but what are the main differences between them?

1 answer

15


std::array

It has semantics equal to array normal C, but it’s a better way to use C++ when you need a sequence of contiguous, fixed-size objects. Obviously it does not decay to pointer as with the array of C, at least implicitly.

Access occurs in O(1) complexity. You cannot insert or delete unless you create another array, but if you need to do that she’s probably the wrong structure.

I say that in C++ you should program in C++ and leave aside everything that exists in C. A good application in C++ will make better use of the resources of this structure than the array raw C, mainly for keeping its size. It leaves nothing to be desired regarding the C mechanism, and can be used with various C algorithms++.

std::vector

It’s like a array, The first big difference is that it allows you to change your size. When you need to change the size there is a processing cost, but there are techniques to prevent the size from being changed with the same frequency as the need for change, in compensation there is some memory waste when not every reserved area is used.

The second major difference is that it is a type by default reference. So even having an access cost The(1) is a little slower to access an element in it than in the std:array that does not have this indirect to reach the data. And of course may have dynamic memory costs, but depends on the allocator used.

Access to the elements can be done safely. The cost (complexity) of the operations (insert and delete) is the same as the std:array, but has methods ready to do for you and take care that everything works, including it invalidates iterators if any operation makes its use invalid. All management is on his account.

Is compatible with the std::array.

There is a recommendation to use it until you have a reason to use another way.

std::list

Is a double-listed. Besides being able to manipulate the size, it is easy to insert or delete elements at any point in the list. But to access its members has a cost O(n), which can create a difficulty to insert or delete if you do not know the exact point where the operation should be done, after all it does not have an index in O(1).

It is not allocated continuously and there is a overhead memory to manage nodes. The processor does not like this type of structure very much and some optimizations may not be used.

Changes in its structure do not affect iterators.

If you need it like you need it std::array it is necessary to convert.

  • 2

    Who negative can say what’s wrong that I correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.