开发者

Assigning a vector of one type to a vector of another type

开发者 https://www.devze.com 2022-12-27 07:20 出处:网络
I have an \"Event\" class. Due to the way dates are handled, we need to wrap this class in a \"UIEvent\" class, whi开发者_Python百科ch holds the Event, and the date of the Event in another format.

I have an "Event" class. Due to the way dates are handled, we need to wrap this class in a "UIEvent" class, whi开发者_Python百科ch holds the Event, and the date of the Event in another format.

What is the best way of allowing conversion from Event to UIEvent and back? I thought overloading the assignment or copy constructor of UIEvent to accept Events (and vice versa)might be best.


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 the other type:

struct UIEvent
{
    UIEvent(const Event&);
};

and use std::copy to copy elements from a vector of one type to a vector of the other:

std::vector<Event> eventVector;
std::vector<UIEvent> uiEventVector;

std::copy(eventVector.begin(), eventVector.end(), 
          std::back_inserter(uiEventVector));

The second option would be to write a non-member conversion function:

UIEvent EventToUIEvent(const Event&);

and use std::transform:

std::transform(eventVector.begin(), eventVector.end(), 
               std::back_inserter(uiEventVector), &EventToUIEvent);

The advantage of doing it this way is that there is less direct coupling between the classes. On the other hand, sometimes classes are naturally coupled anyway, in which case the first option might make just as much sense and could be less cumbersome.


If you can convert an Event to a UIEvent (for example, if UIEvent has a constructor that takes an Event as parameter) then the following will assign one vector onto another:

uievent_vector.reserve(event_vector.size());
uievent_vector.assign(event_vector.begin(), event_vector.end());

Naturally the other way around would work as well if that conversion works.

Alternatively you can use std::copy() to get the same effect. If you can't make the conversion in one way inside the class interface, then write a function that makes the conversion and 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 wish of operator()() in the above function object so you can use that same function object for other conversions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号