Is there a standard way to convert from containerlt;Type1gt; to containerlt;Type2gt;?(是否有从容器转换的标准方法lt;Type1gt;到容器lt;Type2gt;?)
问题描述
我有两个类A
和B
,并且存在一个隐式转换运算符从一个到另一个,所以:
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
是否有将 std::list<A>
转换为 std::list<B>
的标准方法?(甚至从 std::vector<A>
到 std::list<B>
).
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.
不幸的是,我不能使用 boost
,但出于好奇,如果 boost 可以处理这个问题,我也很乐意知道如何处理.
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());
序列容器也有 assign
成员函数,它对赋值语义(与初始化语义相反)做同样的事情.
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>到容器<Type2>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有从容器转换的标准方法<Type1>到容器<Type2>?


基础教程推荐
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04