代码之家  ›  专栏  ›  技术社区  ›  ereOn

有没有一种标准的方法可以将容器<Type1>转换成容器<Type2>?

  •  8
  • ereOn  · 技术社区  · 14 年前

    A B ,并且存在一个隐式转换运算符来从一个转换到另一个,因此:

    A a;
    B b;
    b = a; // Works
    

    std::list<A> std::list<B> ? (甚至从 std::vector<A> 标准::列表<B> ).

    我知道我可以迭代到列表并逐项构建第二个列表,但我想知道是否有更优雅的解决方案。

    我不能用 boost

    1 回复  |  直到 14 年前
        1
  •  15
  •   AnT stands with Russia    14 年前

    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()); // replaces the contents of `l`