I'm kinda new to C++, I have an abstract class (pure virtual) which 2 classes inherits from it. Each derived class holds similar data, only in different STL container (array vs map) I'm overloading the operators of the base class in order to perform, for example, addition of the STL elements. I want to be able to iterate over the elements of the STL, regardless of what type it is.
I've searched for a few days now on generic iterators, and stuff like that, but couldn't find anything.
I don't have too much code to share, as I was unable to do anything. I thought maybe to have my base class hold a template variable which would represent the STL container and then get its iterator in the operator, but again, not sure how to.
protected:
template<class T>
T gStlContainer;
and then accessing
gStlContainer::iterator<double> it;
obviously didn't work.
Any suggestions? Thanks!
EDIT: I'm editing to try and explain better using an example. I'm overloading the + operator in the base (abstract) class, what I want it to do is iterate over each element of the STL container, and add it to another element, for example, Say I have this arrays as STL
arr = [0,1,2,3] // Say it's stored in Derived2 class
arr = [4,5,6,7] // Say it's stored in Derived3 class
These arrays are each stored inside one of the derived classes. When I'm doing
Derived1 = Derived2 + Derived3;
then Derived1 would hold
arr = [4,6,8,10]
Hope it's a bit more clear now. The issues is that it won't always be an array, it can be combining array and map for example. That's why I need the generic iterator, or some solution.
Thanks!
C++ doesn't have generic iterators, but it does have template functions that can be written to operate on any type of iterator. To add all the elements in a container, there's already an algorithm for you. Read about std::accumulate.
You're looking at the problem from the wrong point of view. You could do this, but why would you? Your base class shouldn't implement the method if it's supposed to behave differently, but should delegate the logic to the derived classes.
class Base
{
public:
virtual ~Base() {}
virtual void iterate() = 0;
};
class Derived : Base
{
public:
virtual void iterate() { /*iterate through vector or map or whatever*/ }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With