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

好久不见. 提交于 2019-11-28 07:51:12

问题


I have an "Event" class. Due to the way dates are handled, we need to wrap this class in a "UIEvent" class, which 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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2634279/assigning-a-vector-of-one-type-to-a-vector-of-another-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!