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

后端 未结 7 1062
逝去的感伤
逝去的感伤 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:37

    Rule of thumb: if you don't know the number of elements in advance, or if the number of elements is expected to be large (say, more than 10), use vector. Otherwise, you could also use an array. For example, I write a lot of geometry-processing code and I define a line as an ARRAY of 2 coordinates. A line is defined by two points, and it will ALWAYS be defined by exactly two points. Using a vector instead of an array would be overkill in many ways, also performance-wise.

    Another thing: when I say "array" I really DO MEAN array: a variable declared using an array syntax, such as int evenOddCount[2]; If you consider choosing between a vector and a dynamically-allocated block of memory, such as int *evenOddCount = new int[2];, the answer is clear: USE VECTOR!

提交回复
热议问题