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

8
All containers used to guard data sequentially, but what are the main differences between them?

    
asked by anonymous 04.11.2016 / 17:30

1 answer

13

std::array

It has semantics equal to the normal array of C, but is a better way to use it in C ++ when it needs a contiguous sequence of objects of fixed size. Obviously it does not drop to pointer as occurs with the array of C.

Access occurs in complexity O (1). You can not insert or delete unless you create another array , but if you need to do this it is probably the wrong structure.

I say that in C ++ you should program in C ++ and leave out all that exists in C. A good C ++ application will better take advantage of this framework's resources than the C's array , mainly for storing its size. It leaves nothing to be desired about the C engine, and can be used with various C ++ algorithms.

std::vector

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

The second major difference is that it is a reference type by default. So even having an access cost O (1) is a little slower to access an element in it than in std:array that does not have this indirection to get in the data.

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

It is compatible with std::array .

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

std::list

This is a double-linked list . In addition to being able to manipulate the size, it is easy to insert or delete elements anywhere in the list. But to access its members has an O (N) cost, which can create a difficulty to insert or delete if it does 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 continuously allocated and there is an overhead of memory to manage the nodes. The processor does not like this kind of structure very much and some optimizations can not be used.

Changes to your structure do not affect iterators.

If you need it as a std::array you need to convert.

    
04.11.2016 / 18:14