Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c++ - Assigning a vector of one type to a vector of another type

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...