通过构造函数转换容器

Convert containers via constructor

本文关键字:转换 构造函数      更新时间:2023-10-16

>假设我有类

class A {
   //...
};
struct B {
   explicit B(const A&);
   //...
};

我有一个 A 的容器,我想从中构建一个 B 的容器。 在 c++ 03 中执行此操作的惯用方法是什么?

尝试并失败:

std::vector<A> source = fillSourceObjects();
std::vector<B> target;
// 1) won't compile; presumably I need a static helper function, 
//    but I would like to avoid that
std::transform(source.begin(), source.end(), std::back_inserter(target), B);
std::transform(source.begin(), source.end(), std::back_inserter(target), B::B);
// 2) won't compile; "... error: no match for 'operator=' in '* __result = *__first'
std::copy(source.begin(), source.end(), target.begin());

您可以使用采用序列的 std::vector<T> 构造函数将 A s 序列转换为 B s 序列:

std::vector<B> target(source.begin(), source.end());