C++ - 为 std::vector 创建新的构造函数<double>?
C++ - create new constructor for std::vector<double>?
我已经编写了一个自定义容器类,它包含一个std::vector<double>
实例,工作得很好。为了与其他API兼容,我想将容器的内容导出为std::vector<double>
副本。目前这项工作:
MyContainer container;
....
std::vector<double> vc(container.begin(), container.end());
但如果可能的话,希望能够写:
MyContainer container;
....
std::vector<double> vc(container);
我能(轻松地)创建这样一个std::vector<double>
构造函数吗?
您可以创建到std::vector<double>
:的显式转换
explicit operator std::vector<double>() const {
return std::vector<double>(begin(), end());
}
然后,std::vector<double> vc(container);
将调用std::vector<double>
移动构造函数。
请注意,计算成本高昂的转换通常是不受欢迎的。因此,向量工厂函数可能是一种更明智的方法:
class MyContainer {
public:
using value_type = double;
// ...
};
template<typename Source>
auto to_vector(Source source) {
return std::vector<typename Source::value_type>(source.begin(), source.end());
}
然后你会写:
MyContainer container;
// ...
auto vc = to_vector(container);
这也更通用,因为它适用于任何具有兼容value_type
、begin
和end
成员的对象。
我能(轻松地)创建这样一个std::vector构造函数吗?
不可以,因为这需要更改std::vector
类声明。
不过,您可以为MyContainer
到std::vector<double>
提供强制转换运算符。
您不能也不应该更改您自己没有编写的类的API。但我认为在你的情况下,演员会做得很好。例如(这个需要-std=c++11
):
#include <iostream>
#include <vector>
struct Foo
{
operator std::vector<double> () const
{
return std::vector<double> { 1, 2, 3 };
}
};
int main()
{
Foo foo;
std::vector<double> bar = foo; // Applies the cast operator defined in Foo
std::cout << bar.size() << std::endl; // Prints "3"
return 0;
}
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- C++在数学计算中将double转换为int
- 在c++中为double类型的数组创建一个unique_ptr
- vector<vector<double>> to mxArray using memcpy
- (double) 和 double() 之间的区别
- C++标准是否允许<double>在没有开销的情况下实现 std::可选
- C++ Version Of Double.longBitsToDouble
- 错误:类型"double()"和"double()"的操作数无效到二进制&quo
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- 为什么 nlohmann/json 序列化 "null" 而不是在 double 上"0"?
- 使用 std::vector<double> 访问由 std::unique_ptr<double[2] 管理的数据>
- 将 std::vector<double> 从 C++ 包装到 C 以在 Swift 中使用
- 错误:无法将"<lambda(double)>"转换为"double(*)(double)"
- 如何正确将"strings"转换为"double"?
- 如何在<double>矢量中创建复杂类型的模板<T>?
- "double* grade"、"double *grade"和"double* fn()"有什么区别?
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ