Overhead to using std::vector?

前端 未结 7 1164
星月不相逢
星月不相逢 2021-02-13 04:09

I know that manual dynamic memory allocation is a bad idea in general, but is it sometimes a better solution than using, say, std::vector?

To give a crude e

7条回答
  •  别那么骄傲
    2021-02-13 04:42

    In n is known at compile-time, then you should choose std::array as:

    std::array data; //n is compile-time constant
    

    and if n is not known at compile-time, OR the array might grow at runtime, then go for std::vector:

    std::vector data(n); //n may be known at runtime 
    

    Or in some cases, you may also prefer std::deque which is faster than std::vector in some scenario. See these:

    • C++ benchmark – std::vector VS std::list VS std::deque

    • Using Vector and Deque by Herb Sutter

    Hope that helps.

提交回复
热议问题