将一种类型的向量分配给另一种类型的向量 [英] Assigning a vector of one type to a vector of another type

查看:102
本文介绍了将一种类型的向量分配给另一种类型的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个事件"类.由于日期的处理方式,我们需要将该类包装在"UIEvent"类中,该类保存事件,并以另一种格式显示事件的日期.

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.

允许从Event转换为UIEvent并返回的最佳方法是什么?我认为最好重载UIEvent的赋值或复制构造函数以接受事件(反之亦然)最好.

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&);
};

并使用std::copy将元素从一种类型的向量复制到另一种类型的向量:

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&);

并使用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.

这篇关于将一种类型的向量分配给另一种类型的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆