C++ 将(行)从二维阵列复制到一维阵列
所以我有一个二维数组multiarray[a][b]和另一个数组buf[b]C++ 将(行)从二维阵列复制到一维阵列,c++,multidimensional-array,C++,Multidimensional Array,所以我有一个二维数组multiarray[a][b]和另一个数组buf[b] 我无法将'buf'指定为多数组的一行。执行此操作的确切语法是什么?数组是不可分配的。这方面没有核心语言语法。C++中的数组复制是在库级或用户代码级实现的。 // a 2-D array of char char multiarray[2][5] = { 0 }; // a 1-D array of char, with matching dimension char buf[5]; // set the content
我无法将'buf'指定为多数组的一行。执行此操作的确切语法是什么?数组是不可分配的。这方面没有核心语言语法。C++中的数组复制是在库级或用户代码级实现的。
// a 2-D array of char
char multiarray[2][5] = { 0 };
// a 1-D array of char, with matching dimension
char buf[5];
// set the contents of buf equal to the contents of the first row of multiarray.
memcpy(buf, multiarray[0], sizeof(buf));
如果这应该是C++,如果你确实需要创建一个单独的拷贝<代码> Buf<代码>某个行<代码> i>代码> 2D数组>代码>多数组,那么你可以使用<代码> STD::
#include <algorithm>
...
SomeType multiarray[a][b], buf[b];
...
std::copy(multiarray[i], multiarray[i] + b, buf);
我读到的代码在snort(旧版本)中有类似的功能,它是从tcpdump借来的,可能对您有帮助
/****************************************************************************
*
* Function: copy_argv(u_char **)
*
* Purpose: Copies a 2D array (like argv) into a flat string. Stolen from
* TCPDump.
*
* Arguments: argv => 2D array to flatten
*
* Returns: Pointer to the flat string
*
****************************************************************************/
char *copy_argv(char **argv)
{
char **p;
u_int len = 0;
char *buf;
char *src, *dst;
void ftlerr(char *, ...);
p = argv;
if (*p == 0) return 0;
while (*p)
len += strlen(*p++) + 1;
buf = (char *) malloc (len);
if(buf == NULL)
{
fprintf(stderr, "malloc() failed: %s\n", strerror(errno));
exit(0);
}
p = argv;
dst = buf;
while ((src = *p++) != NULL)
{
while ((*dst++ = *src++) != '\0');
dst[-1] = ' ';
}
dst[-1] = '\0';
return buf;
}如果使用向量:
vector<vector<int> > int2D;
vector<int> int1D;
如果您使用的是c样式数组,一种基本方法是将选定行中的每个元素复制到一维数组:
例如:
//Assuming int2D is a 2-Dimensional array of size greater than 2.
//Assuming int1D is a 1-Dimensional array of size equal to or greater than a row in int2D.
int a = 2;//Assuming row 2 was the selected row to be copied.
for(unsigned int b = 0; b < sizeof(int2D[a])/sizeof(int); ++b){
int1D[b] = int2D[a][b];//Will copy a single integer value.
}
//假设int2D是一个大小大于2的二维数组。
//假设int1D是一个一维数组,其大小等于或大于int2D中的一行。
INTA=2//假设第2行是要复制的选定行。
for(unsigned int b=0;b
语法是一条规则,算法是您可能想要的。您现在有什么代码?您不能分配数组。数组名称不是左值。buf[0]=&multiarray[index];这就是我所拥有的@Chris,但是数组在C中被视为指针,是吗?数组也不是指针。在某些情况下,它们会腐烂,但这不是其中之一。因为a-1似乎不合理,所以投票率上升。我讨厌以否决票的方式开车。
int1D = int2D[A];//Will copy the array at index 'A'
//Assuming int2D is a 2-Dimensional array of size greater than 2.
//Assuming int1D is a 1-Dimensional array of size equal to or greater than a row in int2D.
int a = 2;//Assuming row 2 was the selected row to be copied.
for(unsigned int b = 0; b < sizeof(int2D[a])/sizeof(int); ++b){
int1D[b] = int2D[a][b];//Will copy a single integer value.
}