I'm trying to make my own vector in C++ so I could understand more how it works ! This is the code:
#pragma once
template<typename T>
class Vector {
public:
Vector() {
// allocate 2 elements
ReAlloc(2);
}
void pushBack(const T& value) {
if (m_Size >= m_Capacity) {
ReAlloc(m_Capacity / 2);
}
m_Data[m_Size++] = value;
}
const T& operator[](size_t index) const {
/*
if (index >= m_Size) {
// assert
}
*/
return m_Data[index];
}
T& operator[](size_t index) {
/*
if (index >= m_Size) {
// assert
}
*/
return m_Data[index];
}
const size_t Size() const { return m_Size; }
size_t Size() { return m_Size; }
private:
T* m_Data = nullptr;
size_t m_Size = 0;
size_t m_Capacity = 0;
private:
void ReAlloc(size_t newCapacity) {
// 1. allocate a new block of memory
// 2. copy/move old elements into the new block
// 3. delete the old one
T* newBlock = new T[newCapacity];
if (newCapacity < m_Size) {
m_Size = newCapacity;
}
for (size_t i = 0; i < m_Size; i++) {
newBlock[i] = m_Data[i];
}
delete[] m_Data;
m_Data = newBlock;
m_Capacity = newCapacity;
}
};
However, When I try to use it from main.cpp like this:
#include <iostream>
#include <string>
#include "Vector.h"
#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl
template<typename T>
void PrintVector(Vector<T>& vector) {
for (size_t i = 0; i < vector.Size(); i++) {
println(vector[i]);
}
println("------------------------------------------");
}
int main() {
Vector<std::string> vector;
vector.pushBack("Ahmed");
vector.pushBack("C++");
vector.pushBack("Vector");
PrintVector(vector);
}
The code give me this output:
Ahmed
Vector
------------------------------------------
(process 7540) exited with code -1073740940.
it's not even printing C++ and the code acts weird, whenever I try o change anything the output became more mess, Could anyone tell me what did I do wrong please ?!. Thx ! :)
In your pushBack
function, when the size is greater than or equal to capacity, you are doing:
ReAlloc(m_Capacity / 2);
which doesn't make sense. If you need additional space to add elements, you should increase the capacity of the underlying array, not decrease it by half.
You are probably looking for:
ReAlloc(m_Capacity * 2);
which doubles the underlying capacity.
Here's a working demo, without any segfault.