Posted Joe Chu cpp3 minutes read (About 431 words)0 visits
Design Vector
Design a customized vector container.
Introduction
I am launching a fresh blog series dedicated to object-oriented design with C++. The inspiration behind this initiative stems from my job interviews, where over 70% of the positions requiring C++ skills focused on designing scenarios rather than typical leetcode-style problems. This experience highlighted the significance of understanding design patterns and the principles of object-oriented programming (OOP).
Today, we will explore how to design a vector container in C++. Some basic requirements for our customized vector would be:
pushback(): push an object/element to the end of the vector
popback(): pop an object/element for the end of the vector
size(): get the size of the vector
emplaceback(): contruct an object in-place and push it to the end of the vector
private: voidReAlloc(size_t newCapacity){ // 1. allocate a new block of memory // 2. copy//move old data into new block // 3. delete old data T* newBlock = (T*) ::operatornew(newCapacity * sizeof(T));
// for downsize the vector if (newCapacity < _size) { _size = newCapacity; } for (size_t i = 0; i < _size; i++) { new (&newBlock[i]) T(std::move(_data[i])); } for (size_t i = 0; i < _size; i++) { _data[i].~T(); }