通过构造函数转换容器
Convert containers via constructor
>假设我有类
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());
相关文章:
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- enable_if转换构造函数(静态强制转换,is_base_of)
- 为什么我需要在转换构造函数上引用 this->?
- 为什么在使用转换构造函数编译代码时需要 const 复制构造函数?
- 为什么不对转换构造函数进行隐式强制转换?
- 转换构造函数和运算符都存在且涉及显式性时的行为
- C++ 03 类模板 这是转换构造函数还是转换运算符?以及如何声明解决此问题的方法
- 使用完美转发的模板转换构造函数
- 转换构造函数的参数可以隐式转换吗?
- std::变量转换构造函数行为
- 隐式用户定义的转换不起作用,因为在编译C 时无法识别运算符和转换构造函数
- 为什么不调用模板类中的转换构造函数?
- 转换构造函数的隐式参数
- 转换构造函数:您如何解释C 中给定不同参数的函数
- C++变体:为什么转换构造函数需要大小.(类型)为非零
- C++变体用bool转换构造函数
- 在重载解析期间调用转换运算符,而不是在 c++17 中转换构造函数
- 为什么在没有赋值运算符的情况下调用转换构造函数
- 如何将转换构造函数与指针一起使用?
- 为什么在调用隐式类型转换构造函数之后直接是驱动器