实现一个函数:把一个数组里的所有元素,插入到另一个数组的指定位置。
比如:
函数输入([2,5,3,4,7,0],2,[8,9,6]),输出[2,5,8,9,6,3,4,7,0]。
代码转自:http://blog.csdn.net/wujunokay/article/details/12071299
方法一、使用vector
/* 参数说明: vec_a:数组a pos:插入位置 vec_b:数组b vec_out:输出数组 */ int MakeInsertDataByVec(vector<int> vec_a, int pos, vector<int> vec_b, vector<int>& vec_out) { int nASize = vec_a.size(); int nBSize = vec_b.size(); int i; vector<int>::iterator itorA; vector<int>::iterator itorB; int nCount = 0; //遍历a for(itorA=vec_a.begin(); itorA!=vec_a.end(); itorA++) { if (nCount!=pos) { nCount++; vec_out.push_back(*itorA); } else if(nCount==pos)//当个数=pos时候,开始插入b { nCount++; //遍历b for (itorB = vec_b.begin(); itorB!=vec_b.end(); itorB++) { vec_out.push_back(*itorB); } vec_out.push_back(*itorA); } } return 0; }
方法二、内存拷贝
/* 参数说明: a:数组a aCount:数组a元素个数 pos:插入位置 b:数组b bCount:数组b元素个数 返回: output:输出的数组 */ int* MakeInsertData(int* a, int aCount, int pos, int* b, int bCount) { int* PA=a; int* PB = b; int* output=new int[aCount+bCount+1]; int nCount = 0; memcpy(output, PA, pos*sizeof(int)); nCount = nCount+pos; //memcpy((char*)&output[nCount], PB, bCount*sizeof(int));//这样也是对的 memcpy(output+nCount, PB, bCount*sizeof(int)); nCount = nCount+bCount; //memcpy((char*)&output[nCount], &(PA+pos), bCount*sizeof(int));//这样也是对的 memcpy(output+nCount, PA+pos, (aCount-pos)*sizeof(int)); return output; }
测试代码:
int main() { vector<int> vec_a; vector<int> vec_b; vector<int> vec_c; vec_a.push_back(2); vec_a.push_back(5); vec_a.push_back(3); vec_a.push_back(4); vec_a.push_back(7); vec_a.push_back(0); vec_b.push_back(8); vec_b.push_back(9); vec_b.push_back(6); MakeInsertDataByVec(vec_a, 2, vec_b, vec_c); vector<int>::iterator itorC; for(itorC=vec_c.begin(); itorC!=vec_c.end(); itorC++) { cout << *itorC <<","; } cout << endl; int* a= new int[6]; int* b= new int[3]; a[0]=2; a[1]=5; a[2]=3; a[3]=4; a[4]=7; a[5]=0; b[0]=8; b[1]=9; b[2]=6; int* c ; c = MakeInsertData(a, 6, 2, b, 3); for (int i=0; i<6+3; i++) { cout << c[i] << ","; } delete[] a; a=NULL; delete[] b; b=NULL; delete[] c; c=NULL; cout << endl; return 0; }
测试结果如下:
2,5,8,9,6,3,4,7,0, 2,5,8,9,6,3,4,7,0,