是否有从容器转换为标准方法?到容器

发布于 2024-09-16 15:08:41 字数 478 浏览 2 评论 0原文

我有两个类 AB,并且存在一个隐式转换运算符可以从一个类转换到另一个类,因此:

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

是否有一种标准方法来转换 std::liststd::list ? (或者甚至从 std::vectorstd::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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人哭 2024-09-23 15:08:41

嗯,是的。每个序列容器类型都有一个模板构造函数,该构造函数采用一对迭代器(迭代器范围)作为输入。它可用于从另一个序列构造一个序列,无论序列类型如何,只要序列元素类型可以相互转换即可。例如,

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`

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`
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文