是否有从容器转换为标准方法?到容器?
我有两个类 A
和 B
,并且存在一个隐式转换运算符可以从一个类转换到另一个类,因此:
A a;
B b;
b = a; // Works
是否有一种标准方法来转换 std::list
到 std::list
? (或者甚至从 std::vector
到
std::list
)。
我知道我可以迭代列表并逐项构建第二个列表,但我想知道是否有更优雅的解决方案。
不幸的是我不能使用boost
,但出于好奇作为一个额外的问题,如果boost可以处理这个问题,我也很高兴知道如何处理。
I have two classes A
and B
, and an implicit conversion operator exists to go from one to the other, so that:
A a;
B b;
b = a; // Works
Is there a standard way to convert a std::list<A>
to a std::list<B>
? (Or even from std::vector<A>
to a std::list<B>
).
I know I can iterate trough to the list and build the second list item by item, but I wonder if there is a more elegant solution.
Unfortunately I cannot use boost
but out of curiosity as a bonus question, if boost can handle this, I'd be happy to know how too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,是的。每个序列容器类型都有一个模板构造函数,该构造函数采用一对迭代器(迭代器范围)作为输入。它可用于从另一个序列构造一个序列,无论序列类型如何,只要序列元素类型可以相互转换即可。例如,
序列容器也有
assign
成员函数,它使用赋值语义(而不是初始化语义)执行相同的操作。Well, yes. Each sequence container type has a template constructor that takes a pair of iterators (an iterator range) as an input. It can be used to construct one sequence from another, regardless of the sequence types, as long as the sequence element types are convertible to each other. Like for example
Also sequence containers have
assign
member function which does the same thing with assignment semantics (as opposed to initialization semantics).