I created this simple array class and it works fine but there is 1 issue.... Everytime i want to insert value at some index then i have to do something like array.insert(0, 10);
where 0 is index and 10 is value. Can't i do it something like array[0] = 10;
I have already overrided the [] operator to print value like cout << array[0];
but if i try something like array[0] = 10;
then it throws an error Expression is not assignable
I wish someone helps me btw here is the code....
#include <iostream>
template<typename type, int size>
class Array
{
private:
type array[size];
public:
int len() //returns the number of elements
{
return size;
}
type val(int index) //returns the value at given index
{
return array[index];
}
int memsize() //returns the size of array in bytes
{
return sizeof(array);
}
void pop(int index) //deletes element at given index
{
delete array[index];
}
void insert(int index, type value) //inserts an value at given index
{
if(index >= size)
{
std::cout << "Error! Cannot insert value at unspecified index";
exit(0);
}
else
{
array[index] = value;
}
}
void update(int index, type value) //updates the values at given index
{
if(index >= size)
{
std::cout << "Error! index <" << index << "> not found";
exit(0);
}
else
{
array[index] = value;
}
}
type operator[](int index) //overriding the [] operator so that we can access an element using [index]
{
if(index >= size)
{
std::cout << "Error! Index value over limits";
exit(0);
}
else
{
return array[index];
}
}
};
int main()
{
Array<int, 3> array;
array.insert(0, 10);
array.insert(1, 20);
array[2] = 8; //This line throws Error
//Error (Expression is not assignable)
}
If anyone has any idea to solve this then please help... Thanks in advance to everyone.