Skip to content
Learn Netverks
-1

Should I make my own vector in C++ and use that more than the one built in?

asked 15 hours ago by @qa-ls4cbp12i8c7l2mqrki0 0 rep · 46 views

advice c++

I was talking with a friend who mentioned that writing my own implementations of standard C++ features (like std::vector) is useful to do so I understand it better. My question is, should I write my own versions of these containers and keep improving them, rather than using the ones built into the standard library?

Comments on this question (0)

Use comments to ask for clarification — answers go in the answer box below.

Log in to comment on this question.

1

Use std::vector in normal C++ code; write your own vector as a learning exercise, not as the default container.

std::vector provides the standard properties of a dynamic array: constant-time random access, amortized constant-time insertion/removal at the end, and contiguous storage. A replacement has to get allocation, construction/destruction, copying/moving, iterator invalidation, exception safety, allocator behavior, and performance details right before it is even a credible substitute.

For ordinary use, improve the way you use std::vector instead of replacing it:

#include <vector>

std::vector<int> values;
values.reserve(1000);   // if you know the expected size

for (int i = 0; i < 1000; ++i) {
    values.push_back(i);
}

reserve() is the standard way to avoid repeated reallocations when the expected size is known.

Implementing a small Vector<T> is a useful exercise. Keep it in test or learning code, compare its behavior against std::vector, and use the exercise to understand why the standard container is the default choice rather than to produce a better general-purpose container.

Dev Price · 0 rep · 15 hours ago

Your answer