在我看來,你的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);
}
};
定義幫手結構