Assigning a vector of one type to a vector of another type
I have an "Event" class. Because of the way dates are handled, we need to wrap this class in a "UIEvent" class that contains the event and event date in a different format.
What is the best way to go from event to UIEvent and back? I thought that overloading the assignment constructor or copy of the UIEvent to accept events (and vice versa) might be better.
a source to share
There are two simple options that I can think of.
The first option would be the one you describe: create a constructor that takes an object of a different type:
struct UIEvent
{
UIEvent(const Event&);
};
and use std::copy
to copy elements from one vector to vector of another:
std::vector<Event> eventVector;
std::vector<UIEvent> uiEventVector;
std::copy(eventVector.begin(), eventVector.end(),
std::back_inserter(uiEventVector));
The second option is to write a conversion function other than a member:
UIEvent EventToUIEvent(const Event&);
and use std::transform
:
std::transform(eventVector.begin(), eventVector.end(),
std::back_inserter(uiEventVector), &EventToUIEvent);
The advantage of this method is that there is less direct relationship between classes. On the other hand, sometimes classes are naturally related to each other, in which case the first option may make the same sense and may be less cumbersome.
a source to share
If you can convert Event
to UIEvent
(for example, if it UIEvent
has a constructor that takes an Event
as parameter ), then the following assigns one vector to another:
uievent_vector.reserve(event_vector.size());
uievent_vector.assign(event_vector.begin(), event_vector.end());
Naturally the opposite will work if this conversion works.
Alternatively, you can use std::copy()
to get the same effect. If you cannot do the conversion one way inside the class interface, write a function that does the conversion, then use std::transform()
:
struct to_uievent {
UIEvent operator()(const Event& e) {
// ...
}
};
// ...
std::transform(event_vector.begin(), event_vector.end(),
back_inserter(uievent_vector),
to_uievent());
You can, of course, add as many overloads as you like operator()()
in the above function object so that you can use the same function object for other conversions.
a source to share