C++ 如何将数组中的元素向右移动一个
我需要在不使用向量库的情况下向数组中插入一个值。插入它的方式是替换我要插入数字的索引处的数字。我需要在任意索引中插入一个数字,并通过保留所有值将索引后面的所有内容向右移动。我尝试通过创建一个新数组来实现这一点,但不幸的是没有什么好处C++ 如何将数组中的元素向右移动一个,c++,C++,我需要在不使用向量库的情况下向数组中插入一个值。插入它的方式是替换我要插入数字的索引处的数字。我需要在任意索引中插入一个数字,并通过保留所有值将索引后面的所有内容向右移动。我尝试通过创建一个新数组来实现这一点,但不幸的是没有什么好处 void Vector::insert(int value, int index) { //initializing array to copy from index int* new_arr = new int[curr
void Vector::insert(int value, int index)
{
//initializing array to copy from index
int* new_arr = new int[current];
//copying everything from given index to the end
for(int i = 0; i < current; i++){
if((arr[index+1]) != NULL){
new_arr[i] = arr[index + i];
}
}
//replaces the given value at the given index
arr[index] = value;
//copying before and after the index into one array
int* total_arr = new int[current+1];
//before index
for (int i = 0; i < index; i++){
total_arr[i] = arr[i];
}
//after index
for(int i = index; i< current+1; i++){
total_arr[i] = new_arr[i];
}
capacity += 1;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
arr[i] = total_arr[i];
}
//replaces the given value at the given index
arr[index] = value;
//copying before and after the index into one array
int* total_arr = new int[current+1];
//before index
for (int i = 0; i < index; i++){
total_arr[i] = arr[i];
}
//after index
for(int i = index; i< current+1; i++){
total_arr[i] = new_arr[i];
}
for(int i = 0; i<current+1; i++){
std::cout<<total_arr[i]<<std::endl;
}
for(int i = 0; i<capacity+1; i++){
std::cout<<total_arr[i]<<std::endl;
}
capacity += 1;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
arr[i] = total_arr[i];
}
}
void Vector::insert(int值,int索引)
{
//正在初始化要从索引复制的数组
int*new_arr=新int[当前];
//将所有内容从给定索引复制到末尾
对于(int i=0;i 对于(inti=0;i,您的代码看起来太长太复杂了
在不知道类的规范的情况下,实现应该是这样的(假设arr
是指向数据数组的指针,current
是数组中的元素数):
void Vector::insert(int值,int索引)
{
int*new_arr=新int[当前+1];
//插入前元素的位置不会更改
对于(int i=0;i
?
void Vector::insert(int value, int index)
{
int* new_arr = new int[current+1];
// positions of elements before insertion won't change
for (int i = 0; i < index; i++) new_arr[i] = arr[i];
// the element to insert
new_arr[index] = value;
// positions of elements after insertion will move by one
for (i = index; i < current; i++) new_arr[i + 1] = arr[i];
// change the arrays
int* old_arr = arr;
arr = new_arr;
delete[] old_arr;
current++;
}