如何将用户输入添加到数组或删除?C
How to add user input to array or remove it? C++
说我获取用户输入。如果它们输入的内容尚未在数组中(我该如何检查数组?),请将其添加到数组中。反之亦然,我如何从给定用户输入的数组中删除一些内容。
示例:
string teams[] = {"St. Louis,","Dallas","Chicago,","Atlanta,"};
cout <<"What is the name of the city you want to add?" << endl;
cin >> add_city;
cout <<"What is the name of the city you want to remove?" << endl;
cin >> remove_city;
内置数组的大小是不变的:您既不能删除元素,否则您无法添加任何元素。我建议使用std::vector<std::string>
,而是:将元素添加到std::vector<T>
可以使用push_back()
完成。要删除元素,您将找到一个元素,例如,使用std::find()
,然后使用erase()
删除它。
如果您需要使用内置阵列(尽管我看不出有任何充分理由),则您将使用new std::string[size]
在堆上分配一个数组并保持其尺寸,并使用delete[] array;
在适当的时间释放内存。
使用数组,您可以用char*(例如"空")处理空数组单元格。要查找您在数组中搜索的项目,然后查找"替换"或添加。
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;
}
}
但我确实同意使用向量是一种更有效的方法,这只是一种创造性的方法来吸引您的思维思维。
要在数组中添加信息,您可以做这样的事情:
for (int i = 0; i < 10; i++)
{
std::cout << "Please enter the city's name: " << std::endl;
std::getline(cin, myArray[i]);
}
我不确定从数组中删除某些内容是什么意思。您是否要将元素的值设置为0,这将导致{"城市1","城市2",0,"城市3}"。要填充其空间,这将导致{"城市1","城市2","城市3"}?
相关文章:
- 将数组的地址分配给变量并删除
- 你能帮我解决删除数组 c++ 中重复值的挑战吗?
- 如何在C++中删除静态数组?
- 删除指针数组 (C++) 中的元素
- 删除动态数组时未定义标识符
- 在命令行上将输入显示到数组中时如何删除 ./a.out?
- C++数组删除的例外
- C++:指向对象的指针数组 - 删除元素时程序崩溃>
- 你如何打印出使用数组删除某些字符的回文
- 类数组 - 删除操作
- 何时从数组删除类指针
- 从自定义数据类型向量数组C 删除
- 动态数组删除
- 动态数组C++(删除)
- 动态数组删除旧指针并将其设置为新数组C++
- C++ 字符数组删除重复字符
- 使用数组删除记录
- 数组删除导致EXC_BAD_ACCESS错误
- 为什么常规删除运算符在需要数组删除运算符时起作用
- 智能指针数组删除器