On Apr 16, 10:05 am, nw <n...@soton.ac.uk> wrote:
> Hi All,
>
> I currently have a vector of objects (lets call them MyObject). I want
> to perform various operations regularly on the whole vector, for
> example find the maximum, average, or operations not dissimilar to
> that. So as I see it I have 3 options:
>
> 1. Implement these operations as functions
> 2. Derive a class from vector (from googling people seem to think this
> is a bad idea)
> 3. Encapsulate the vector in an object.
>
> I'm tending toward option 1 at the moment and perhaps making my
> functions generic?
>
> What does comp.lang.c++ think?
>
> Any advice appreciated!
>
> #include <iostream>
> #include <vector>
>
> using namespace std;
>
> class MyObject {
>
> int v1;
> int v2;
> int v3;
>
> };
>
> class MyObjectSet {
> public:
>
> vector<MyObject> vec;
>
> int max() {
> // Would find maximum value in o
>
> return 1;
> }
>
> };
>
> int main() {
> MyObject o;
>
> MyObjectSet s;
>
> s.vec.push_back(o);
>
> }
You should, IMO, encapsulate the vector in a class and write methods
that make the calculations
class MyContainer
{
std::vector
public:
MyContainer();
~MyContainer();
GetAverage();
GetMax();
};
or
Write template functions that just take a begin and end iterator,
along with a user defined functor for getting a integral value from
the class type.
I would also be sure I am not writing anything over again that already
exists in <algorithm>
|