guys why we use <vector> ,

Recommended Answers

All 2 Replies

Now that we have C++11 there are two options when you want an array object and don't want to use a native array. If you want an array of a fixed size you should use a std::array. This has the benefit over native arrays where if you pass it to a function you no longer lose the size of the array as it doesn't decay into a pointer.

If you need dynamic memeory allocation(ie you don't know how many things you are going to need to store) then you want to use a std::vector. A vector can resize durring runtime and handles all of the memory managment for you.

The main difference between a vector and an array, in a C++ sense, is that vectors do automatic dynamic memory management, whereas arrays are fixed.

You should always prefer using std::vector<T> since the destruction will be automatic once the vector goes out scope and the allocated memory will be placed neatly on the heap and all the memory will be handled for you. std::vector<T> gives you everything you get in an array and even a guarantee that the elements will be contiguously stored in memory.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.