c++ - 分配不同类型的多维 vector

标签 c++ c++11 vector

假设我有一个 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;
}

如果两个 vector 在内部使用相同的类型,我可以只使用赋值运算符(参见 C++ copying multidimensional vector):

i = d;

如果 vector 在内部存储不同的类型,但是是一维的,我可以这样做:

i.assign(begin(d), end(d));

两者的意图都非常明显,我认为我的多维方法解决方案并非如此。有没有更好的方法或公认的习惯用法来做到这一点?

最佳答案

在我看来,您的 2D vector 解决方案是一个很好的解决方案。 当您必须复制 vector 的 vector 的 N 维 vector 时,问题就出现了...

假设您想要一个函数 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);
    }
 };

关于c++ - 分配不同类型的多维 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45332266/

相关文章:

c++ - round 函数返回错误的双重估计

shm_open : DSO Missing From Command Line 上的 C++ Boost 库 undefined reference

c++ - 原始套接字接收 1504 个字节 (MTU = 1500)

c++ - 使用 lambda 创建 unordered_set

java - 如何从数组中获取 5 个数字的序列

c++ - 什么更有效率? vector.assign 与 vector.erase

c++ - Qt - 在 Linux DE 上将窗口提升到当前桌面/工作区

c++ - Google测试-生成用于模板类实例化的值

c++ - 氧气错误 : Found ';' while parsing initializer list

C++ 在没有初始化的情况下制作/命名 vector (在 while 循环中)