Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

c++ - Advantages of using arrays instead of std::vector?

I'm currently seeing a lot of questions which are tagged C++ and are about handling arrays.
There even are questions which ask about methods/features for arrays which a std::vector would provide without any magic.

So I'm wondering why so much developers are chosing arrays over std::vector in C++?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general, I strongly prefer using a vector over an array for non-trivial work; however, there are some advantages of arrays:

  • Arrays are slightly more compact: the size is implicit.
  • Arrays are non-resizable; sometimes this is desirable.
  • Arrays don't require parsing extra STL headers (compile time).
  • It can be easier to interact with straight-C code with an array (e.g. if C is allocating and C++ is using).
  • Fixed-size arrays can be embedded directly into a struct or object, which can improve memory locality and reducing the number of heap allocations needed.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...