[英]Assigning multi-dimensional vectors with different types
假设我有一个std::vector<std::vector<double>> d
并想将其分配给std::vector<std::vector<int>> i
; 我能想到的最好的是:
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<vector<double>> d = { {1.0, 2.0}, {3.0, 4.0} };
vector<vector<int>> i;
for_each(begin(d), end(d), [&i](vector<double> &x) {
i.emplace_back(begin(x), end(x));
}
);
return 0;
}
如果两个向量内部都使用相同的类型,则可以使用赋值运算符(请参见C ++复制多维向量 ):
i = d;
如果向量在内部存储不同类型,但是是一维的,我可以这样做:
i.assign(begin(d), end(d));
两者的意图确实很明显,我对多维方法的解决方案并不这么认为。 是否有更好的方法或公认的习惯用法?
在我看来,您对于2D向量的解决方案是一个很好的解决方案。 当您必须复制向量的向量的N维向量时,就会出现问题。
假设您需要一个在以下情况下起作用的函数copy_multi_vec()
std::vector<std::vector<std::vector<double>>> vvvd
{ { {1.0, 2.0, 3.0}, { 4.0, 5.0, 6.0} },
{ {7.0, 8.0, 9.0}, {10.0, 11.0, 12.0} } };
std::vector<std::vector<std::vector<int>>> vvvi;
copy_multi_vec(vvvi, vvvd);
在这种情况下,可以在帮助器类中使用部分模板专门化功能。 举个例子
template <typename T1, typename T2>
struct cmvH
{ static void func (T1 & v1, T2 const & v2) { v1 = v2; } };
template <typename T1, typename T2>
struct cmvH<std::vector<T1>, std::vector<T2>>
{
static void func (std::vector<T1> & v1, std::vector<T2> const & v2)
{
v1.resize( v2.size() );
std::size_t i { 0U };
for ( auto const & e2 : v2 )
cmvH<T1, T2>::func(v1[i++], e2);
}
};
template <typename T1, typename T2>
void copy_multi_vec (T1 & v1, T2 const & v2)
{ cmvH<T1, T2>::func(v1, v2); }
或者,如果您想在最后一级使用assign()
方法,则可以按如下方式定义帮助程序结构:
template <typename, typename>
struct cmvH;
template <typename T1, typename T2>
struct cmvH<std::vector<T1>, std::vector<T2>>
{
static void func (std::vector<T1> & v1, std::vector<T2> const & v2)
{
v1.resize( v2.size() );
v1.assign( v2.cbegin(), v2.cend() );
}
};
template <typename T1, typename T2>
struct cmvH<std::vector<std::vector<T1>>, std::vector<std::vector<T2>>>
{
static void func (std::vector<std::vector<T1>> & v1,
std::vector<std::vector<T2>> const & v2)
{
v1.resize( v2.size() );
std::size_t i { 0U };
for ( auto const & e2 : v2 )
cmvH0<std::vector<T1>, std::vector<T2>>::func(v1[i++], e2);
}
};
是否有更好的方法或公认的习惯用法?
一次分配数组的一个元素并没有困难。 您能做的最好的就是创建一个函数来帮助它。
例如,您可以使用:
template <typename T1, typename T2>
void vector_copy(std::vector<std::vector<T1>>& dest,
std::vector<std::vector<T2>> const& src)
{
// Add the code to do the copy
}
然后使用
vector_copy(d, i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.