C++ std::vector vs array in the real world

后端 未结 7 1051
逝去的感伤
逝去的感伤 2020-11-27 16:56

I\'m new to C++. I\'m reading "Beginning C++ Through Game Programming" by Michael Dawson. However, I\'m not new to programming in general. I just finished a cha

7条回答
  •  一整个雨季
    2020-11-27 17:33

    It's a rare case in the real world where you deal with fixed collections, of a known size. In almost all cases there is a degree of the unknown in exactly what size of data set you will be accommodating in your program. Indeed it is the hallmark of a good program that it can accomodate a wide range of possible scenarios.

    Take these (trivial) scenarios as examples:

    • You have implemented a view controller to track AI combatants in a FPS. The game logic spawns a random number of combatants in various zones every couple of seconds. The player is downing AI combatants at a rate known only at run time.
    • A lawyer has accessed the Municipal Court website in his state and is querying the number of new DUI cases that came in over the night. He chooses to filter the list by a set of variables including time the accident occurred, zip code, and arresting officer.
    • The operating system needs to maintain a list of memory addresses in use by the various programs running on it. The number of programs and their memory usage changes in unpredictable ways.

    In any of these cases a good argument can be made that a variable size list (that accommodates dynamic inserts and deletes) will perform better than a simple array. With the main benefits coming from reduced need to alloc/dealloc memory space for the fixed array as you add or remove elements from it.

提交回复
热议问题