是否有一个标准的方法来转换容器< Type1>到container< Type2>? [英] Is there a standard way to convert from container<Type1> to container<Type2>?
问题描述
我有两个类 A
和 B
,存在一个隐式转换运算符,因此:
A a;
B b;
b = a; // Works
有一个标准的方法来转换 std :: list< ; A>
到 std :: list< B>
? (或者甚至从 std :: vector< A>
到 std :: list< B>
p>
我知道我可以遍历到列表,并逐个构建第二个列表项,但我想知道是否有更优雅的解决方案。
不幸的是我不能使用 boost
但出于好奇,作为一个奖金问题,如果boost可以处理这个,我会也很高兴知道如何。
好的,是的。每个序列容器类型都有一个模板构造函数,它使用一对迭代器(迭代器范围)作为输入。它可以用于从另一个构造一个序列,而不管序列类型,只要序列元素类型可以彼此转换。例如
std :: vector< A> v;
...
std :: list< B> l(v.begin(),v.end());
顺序容器还有 assign
成员函数做与分配语义相同的事情(与初始化语义相反)。
std :: vector< A> v;
std :: list< B> l;
...
l.assign(v.begin(),v.end()); //替换`l`的内容
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.
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
std::vector<A> v;
...
std::list<B> l(v.begin(), v.end());
Also sequence containers have assign
member function which does the same thing with assignment semantics (as opposed to initialization semantics).
std::vector<A> v;
std::list<B> l;
...
l.assign(v.begin(), v.end()); // replaces the contents of `l`
这篇关于是否有一个标准的方法来转换容器< Type1>到container< Type2>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!