Reputation:
I have 2 classes:
class Item;
class Component;
And I have a function to generate a vector
of Item
s from a vector
of Component
s
static vector<Item> generateItemsFromComponents( vector<Component> components )
{
vector<Item> vi;
// ...
return vi;
}
My question is, where do I declare this function? In the Item
class or in the Component
class? Or the class design is wrong? Maybe suggest better methods to achieve this?
Upvotes: 0
Views: 70
Reputation: 23803
First, if there is a 1 to 1 conversion function from a Component
to an Item
, you should consider :
Component
, e.g. Item ToItem();
, ore.g :
operator const Item&() const;
Once you have the single conversion function available, the method that operates on containers does not really belong to any of your existing interfaces (unless you have a class for containers of Components already), so it makes sense to declare a free function :
Example:
vector<Item> generateItemsFromComponents( const vector<Component>& components )
{
vector<Item> vi;
for(auto& comp in components)
vi.push_back(comp.ToItem());
return vi;
}
However, as pointed by @chris, using std::transform
directly, together with a lambda, makes things easier:
Example:
vector<Item> vi;
transform(begin(comp), end(comp), back_inserter(vi), [](Component c){ return c.ToItem(); }
The advantages of this last method:
comp
could be any standard compliant container, not just a vector
.Answer:
<algorithm>
together with this functionUpvotes: 1