How about extending your class by inheritance, then you can use all the STL algorithms with MyClass. You define MyClass as an extension of a Sequence Container, after which you inherit the Sequence public interface, and your object can be operated on by STL algorithms. Writing your own loops is o.k., but using STL to the full extent will result in more readible and easily maintainable code, you need to only be careful when working with the algorithms to ensure the efficiency (e.g. using range member functions v.s. single element ones).
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <numeric>
template
<
typename Type,
template
<
typename Element,
typename Allocator=std::allocator<Element>
> class Sequence
>
class MyClass
:
public Sequence<Type>
{
public:
MyClass()
:
Sequence<Type>()
{}
template<typename Iterator>
MyClass(Iterator begin, Iterator end)
:
Sequence<Type>(begin, end)
{}
};
template<typename Type>
class add_element
{
Type const& t_;
public:
add_element(Type const& t)
:
t_(t)
{}
template<typename Element>
void operator()(Element & lhs)
{
lhs += t_;
}
};
using namespace std;
int main(int argc, const char *argv[])
{
MyClass<int, vector> m;
m.push_back(0);
m.push_back(1);
m.push_back(2);
m.push_back(3);
copy(m.begin(), m.end(), ostream_iterator<int>(cout, " "));
cout << endl;
for_each(m.begin(), m.end(), add_element<int>(-10));
copy(m.begin(), m.end(), ostream_iterator<int>(cout, " "));
cout << endl;
MyClass<int,vector>::value_type sum = accumulate(m.begin(), m.end(), 0);
cout << "sum = " << sum << endl;
return 0;
}
Outputs:
0 1 2 3
-10 -9 -8 -7
sum = -34
Similarly, you can now work with std::accumulate to compute the sum of elements, std::sort to sort MyObject, etc.