array vs vector vs list

前端 未结 8 751
日久生厌
日久生厌 2020-11-28 20:34

I am maintaining a fixed-length table of 10 entries. Each item is a structure of like 4 fields. There will be insert, update and delete operations, specified by numeric posi

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 21:02

    Prefer an std::vector over and array. Some advantages of vector are:

    • They allocate memory from the free space when increasing in size.
    • They are NOT a pointer in disguise.
    • They can increase/decrease in size run-time.
    • They can do range checking using at().
    • A vector knows its size, so you don't have to count elements.

    The most compelling reason to use a vector is that it frees you from explicit memory management, and it does not leak memory. A vector keeps track of the memory it uses to store its elements. When a vector needs more memory for elements, it allocates more; when a vector goes out of scope, it frees that memory. Therefore, the user need not be concerned with the allocation and deallocation of memory for vector elements.

提交回复
热议问题