I have a class that accepts STL containers and stores them in a vector. I have a display function that loops through all the elements of all the added containers as if they were appended to each other. This is what I'm trying to emulate with my at() function and the subscript operator overload as well.
template<typename T, typename C = typename T::value_type>
class MyClass
{
private:
std::vector<T*> myOwnVectors;
public:
void add(T* addedContainer)
{
myOwnVectors.push_back(addedContainer);
}
void displayMyContent() const
{
for (auto* j : myOwnVectors)
{
for (auto&& i : *j)
{
std::cout << i << " ";
}
std::cout << std::endl;
}
}
int size() const {
int s = 0;
for (auto* j : myOwnVectors)
{
for (auto&& i : *j)
{
s++;
}
}
return s;
}
C at(int a) const {
C result = NULL;
int numberOfItemsSoFar = 0;
int numberOfItemsProcessed = 0;
for (int i = 0; i < myOwnVectors.size(); i++)
{
T currentVector = *myOwnVectors.at(i);
numberOfItemsSoFar += currentVector.size();
if (a < numberOfItemsSoFar)
{
result = currentVector[a-numberOfItemsProcessed];
break;
}
numberOfItemsProcessed += currentVector.size();
}
return result;
}
C& operator[](int a) {
C result = NULL;
int numberOfItemsSoFar = 0;
int numberOfItemsProcessed = 0;
for (int i = 0; i < myOwnVectors.size(); i++)
{
T currentVector = *myOwnVectors.at(i);
numberOfItemsSoFar += currentVector.size();
if (a < numberOfItemsSoFar)
{
result = currentVector[a - numberOfItemsProcessed];
break;
}
numberOfItemsProcessed += currentVector.size();
}
return result;
}
C operator[](int a) const {
C result = NULL;
int numberOfItemsSoFar = 0;
int numberOfItemsProcessed = 0;
for (int i = 0; i < myOwnVectors.size(); i++)
{
T currentVector = *myOwnVectors.at(i);
numberOfItemsSoFar += currentVector.size();
if (a < numberOfItemsSoFar)
{
result = currentVector[a - numberOfItemsProcessed];
break;
}
numberOfItemsProcessed += currentVector.size();
}
return result;
}
};
I do this in main:
std::vector<double> vek;
vek.push_back(1.2);
vek.push_back(3.2);
MyClass<std::vector<double> > vek2;
vek2.add(&vek);
vek[0] = 4.45;
vek2.displayMyContent();
And this works, the display function displays the correct results with 4.45. However if I keep doing this:
vek2[1] = 6.3;
vek2.displayMyContent();
The change is not visible. Why and how do I change my code so that I can modify vek2 content like this?