在我看来,您对 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);
}
};