使用数组,您可以使用 char* 处理空数组单元,例如“EMPTY”。要查找您在数组中搜索的项目,并找到“替换”或添加它。
const char * Empty = "EMPTY";
cout << "Please enter a city you want to add:"
cin >> city;
for(int i = 0; i < Arr_Size; i++) //variable to represent size of array
{
if(Arr[i] == Empty) //check for any empty cells you want to add
{
//replace cell
}
else if(i == Arr_Size-1) //if on last loop
cout << "Could not find empty cell, sorry!";
}
至于删除一个单元格:
cout << "Please enter the name of the city you would like to remove: ";
cin >> CityRemove;
for(int i = 0; i < Arr_Size; i++)
{
if(Arr[i] == CityRemove)
{
Arr[i] = Empty; //previous constant to represent your "empty" cell
}
else if(i == Arr_Size - 1) //on last loop, tell the user you could not find it.
{
cout << "Could not find the city to remove, sorry!";
}
}
在跳过“空”单元格时打印数组//打印数组
for(int i = 0; i < Arr_Size; i++)
{
if(Arr[i] != Empty) //if the cell isnt 'empty'
{
cout << Arr[i] << endl;
}
}
但我确实同意使用矢量将是一种更有效的方法,这只是一种让你思考的创造性方法。