C++ - Sample Vector Implementation
I have given here a sample vector implementation.
1. You can add and delete elements at the end
2. You can use Index operator [] to access the elements in the array.
3. I have made vector size fixed to ease the implementation
Source Code
template<class VecType = int>
class MyVector
{
public:
int m_numElements;
int m_currentSize;
VecType *m_pData;
MyVector(int nMaxElements)
{
m_numElements = nMaxElements;
m_pData = new VecType[nMaxElements];
m_currentSize = -1;
}
int GetLength()
{
return m_currentSize + 1; // Add 1 as it is zero based index
}
// Adds the element at the end
bool AddElement(VecType data)
{
m_currentSize++;
if(m_currentSize - 1 >= m_numElements)
return false; // Maximum threshold reached
m_pData[m_currentSize] = data;
return true;
}
// 0 based index
bool ModifyElement(int pos, VecType data)
{
if(pos <= m_currentSize)
{
m_pData[pos] = data;
return true;
}
return false;
}
bool DeleteElement()
{
if(m_currentSize < 0)
return false; // No elements in the vector
m_currentSize--;
return true;
}
VecType operator [] (int index)
{
if(index > m_currentSize)
throw -1;
return m_pData[index];
}
void DisplayVector()
{
for(int i = 0; i < GetLength(); i++)
{
std::cout << m_pData[i];
if( i == GetLength() - 1)
std::cout << "\n";
else
std::cout << ", ";
}
}
void MultiplyValues(VecType value)
{
for(int i = 0; i < GetLength(); i++)
{
m_pData[i] *= value;
}
}
};
int main()
{
MyVector<double> vec(10);
vec.AddElement(12.5);
vec.AddElement(12.6);
vec.AddElement(12.7);
vec.AddElement(12.8);
std::cout << "\n\nAfter adding four elements in the vector\n";
vec.DisplayVector();
std::cout << "\n\nAfter multiplying by 10 with each element in the vector\n";
vec.MultiplyValues(10);
vec.DisplayVector();
std::cout << "\n\nAfter deleting two elements in the vector\n";
vec.DeleteElement();
vec.DeleteElement();
vec.DisplayVector();
std::cout << "\n\nAfter adding three elements in the vector\n";
vec.AddElement(22.7);
vec.AddElement(22.8);
vec.AddElement(22.9);
for(int i = 0; i < vec.GetLength(); i++)
std::cout << vec[i] << "\n";
std::cout << "\n\n";
return 0;
}
Output
After adding four elements in the vector
12.5, 12.6, 12.7, 12.8
After multiplying by 10 with each element in the vector
125, 126, 127, 128
After deleting two elements in the vector
125, 126
After adding three elements in the vector
125
126
22.7
22.8
22.9
Press any key to continue . . .
|