关于给动态数组删除元素的有关问题
关于给动态数组删除元素的问题
代码如下。编译没有问题,但是当运行到
Would you like to delete some elements?
的时候,就会出错跳出,检查了半天也不知道是什么原因。
这个程序很简单,最主要的就是deleteEntry这个函数,该函数将在结束时删除原动态数组,并返回一个新动态数组。三个参数中,第一个参数是原动态数组的名字;第二个是其维数,因为删除元素后会变,所以用了call-by-reference传递类型;最后一个是要删除的元素(如果没找到这个元素,那么返回原来的动态数组)。
------解决方案--------------------
指针用=的话,改变的是指针所指向的地址,不会把里面的内容拷贝过去的。这样说你明白了么?
你要自己用循环一项项的拷贝过去,而不是 a=b;懂吗?比如:
------解决方案--------------------
代码如下。编译没有问题,但是当运行到
Would you like to delete some elements?
的时候,就会出错跳出,检查了半天也不知道是什么原因。
这个程序很简单,最主要的就是deleteEntry这个函数,该函数将在结束时删除原动态数组,并返回一个新动态数组。三个参数中,第一个参数是原动态数组的名字;第二个是其维数,因为删除元素后会变,所以用了call-by-reference传递类型;最后一个是要删除的元素(如果没找到这个元素,那么返回原来的动态数组)。
//
#include <iostream>
#include <string>
inline void keep_window_open()
{
using std::cout;
cout << "\nPress any key to exit:";
getchar();
}
std::string* deleteEntry(std::string *dynamicArray, int& size, std::string newEntry);
// Precondition: size is the SIZE of dynamicArray[], a dynamically allocated array
// Postcondition: newEntry, if can be found in dynamicArray, is deleted,
// while all of the other elements are preserved in a new array
void display(std::string *array, const int size);
// Postcondition: as its name implies
int main()
{
using namespace std;
int size;
cout<<"Input the size of the original string array:\t";
cin>>size;
while(size <= 0)
{
cout<<"\nThe size must be a positive integer!\n";
cin>>size;
}
string *sArray=new string [size];
for(int i=0; i < size; ++i)
{
cout<<"The "<<i+1<<"th string:\t";
cin>>sArray[i];
}
string *newArray;
newArray=sArray;
cout<<"\nThis is the array you gave:\n";
display(newArray,size);
char decision;
cout<<"\nWould you like to delete some elements?\n";
cin>>decision;
if(decision != 'n' && decision != 'N')
{
cout<<"\nDetermine which element you want to delete from it:\n";
string newEntry;
while(cin>>newEntry)
{
newArray=deleteEntry(newArray,size,newEntry);
cout<<"\nAfter the deletion, it becomes:\n";
display(newArray,size);
cout<<endl;
}
cin.clear();
}
keep_window_open();
}
std::string* deleteEntry(std::string* dynamicArray, int& size, std::string newEntry)
{
std::string *newArray;
int original_size = size;
bool match = false;
for(int i=0; i < original_size; ++i)
{
if(dynamicArray[i]==newEntry)
{
--size;
if(match == false)
match=true;
}
}
newArray=new std::string [size];
if(match == false)
{
newArray=dynamicArray;
}
else
{
for(int j=0,k=0; j<size; ++j)
{
while(k<original_size)
{
if(dynamicArray[k] != newEntry)
{
newArray[j]=dynamicArray[k];
++k;
break;
}
else
++k;
}
}
}
delete []dynamicArray;
return newArray;
}
void display(std::string *array, const int size)
{
for(int i=0; i != size; ++i)
std::cout<<array[i]<<std::endl;
}
动态数组
删除
------解决方案--------------------
指针用=的话,改变的是指针所指向的地址,不会把里面的内容拷贝过去的。这样说你明白了么?
你要自己用循环一项项的拷贝过去,而不是 a=b;懂吗?比如:
for(int i=0;i<size;i++)
newArray[i]=dynamicArray[i];
------解决方案--------------------