这有点棘手,但您可以使用模板递归来帮助您在编译时几乎完全完成分配。我知道这不是您正在寻找的东西,但我认为这是值得的 :-)
代码如下:
#include <vector>
using namespace std;
typedef vector<vector<int> > vector2d;
template<size_t K, size_t M, size_t N>
struct v_copy {
static void copy(vector2d& v, int(&a)[M][N])
{
v[K - 1].assign(a[K - 1], a[K - 1] + N);
v_copy<K - 1, M, N>::copy(v, a);
}
};
template<size_t M, size_t N>
struct v_copy<1, M, N> {
static void copy(vector2d& v, int(&a)[M][N])
{
v[0].assign(a[0], a[0] + N);
}
};
template<size_t M, size_t N>
void copy_2d(vector2d& v, int(&a)[M][N])
{
v_copy<M, M, N>::copy(v, a);
}
int main()
{
int A[2][3] = {{0, 1, 2}, {10, 11, 12}};
vector2d vector(2);
copy_2d(vector, A);
}
它需要一个结构,因为在 C++ 中你不能对函数进行部分特化。顺便说一句,使用 gcc 版本 4.5.0 编译它,此代码生成与
相同的程序集
vector[1].assign(A[1], A[1] + 3);
vector[0].assign(A[0], A[0] + 3);
用不同类型的二维数组编译应该不是很难。