在创建数组后的程序中,用户可以选择和删除数组中的一个元素。
之后,程序将显示不包含此元素的数组。
此作业的要求是使用指针。
using namespace std;
int main()
{
int *x = NULL;
int n;
int cyfry;
cout << "podaj dlugosc listy\n"; // array lenght
cin >> n;
x = new int[n];
cout << "podaj cyfry do listy\n";
for (int i = 0; i < n; i++) {
cin >> cyfry;
x[i] = cyfry; // input values to array
}
for (int i = 0; i < n; i++) // values in array
cout << x[i] << ",";
}
答案 0 :(得分:0)
想象一下您要删除用户输入的数组元素中的一个的情况。 这不是一个完美的解决方案,因为newArray仅少了1个元素,并且您需要删除所有元素。但这是因为您有了如何做的想法!您还没有尝试过一件事情(至少从您给我们看的东西上)。
将此汇总为您已经拥有的代码:
newArray = new int[n-1];
int toDelete;
cin>>toDelete;
int j=0;
/*this deletes ALL elements that are, for example, "2" of the array of ints.
If you want to delete only the first found,
you can use a boolean (or a int found=0;),
and in the if case, use this found*/
for(int i=0;i<n;i++){
if(toDelete!=x[i]){
/*we use "j" because newArray has 1 less element than x. So we will be adding numbers
in case the element is the one we want to delete, we do not add it, so j does not sum up. */
newArray[j]=x[i];
j++;
}
}
在您的代码中for
循环中执行此操作,然后执行与代码有关的操作!希望这个例子能解决您的疑问!
编辑:在这种情况下(如问题几个月前的几个小时前所问),在这种情况下,您只想删除元素的第一次遇到:f.e:
[1,2,3,1,2,3,1,2,3]
,要删除的元素为2,最后一个数组:[1,3,1,2,3,1,2,3]
#include <iostream>
using namespace std;
int main()
{
int size=9;
int* firstArray=new int[size];
//just an example to add up the array. This is quite dirty, but as to see the easy example
firstArray[0]=1;
firstArray[1]=2;
firstArray[2]=3;
firstArray[3]=1;
firstArray[4]=2;
firstArray[5]=3;
firstArray[6]=1;
firstArray[7]=2;
firstArray[8]=3;
for (int i=0;i<size;i++)
cout<<firstArray[i];
cout<<endl;
int* newArray = new int[size-1];
int toDelete;
cin>>toDelete;
int j=0;
bool counter=false; //this counter will tell us if we have deleted it once
//[1,2,3,1,2,3,1,2,3]
for(int i=0;i<size;i++){
//if the element we want to delete, is not in the array
if(toDelete!=firstArray[i]){
newArray[j]=firstArray[i];
j++;
}
//if we find the element to delete and we have not deleted it yet, we dont copy it
else if (toDelete==firstArray[i] && counter==false) {
counter=true;
}
//if we have already deleted it, nothing.
else if (toDelete==firstArray[i] && counter==true) {
newArray[j]=firstArray[i];
j++;
}
}
for (int i=0;i<size-1;i++)
cout<< newArray[i];
}
答案 1 :(得分:0)
这里:
int main()
int* wskaznik = NULL;
int ile;
int cyfry;
cout << "podaj dlugosc listy\n";
cin >> ile;
wskaznik = new int[ile];
cout << "podaj cyfry do listy\n";
for (int i = 0; i < ile; i++) {
cin >> cyfry;
wskaznik[i] = cyfry;
}
for (int i = 0; i < ile; i++)
cout << wskaznik[i] << ",";
int* n_wskaznik = new int[ile - 1];
int usun;
/ int j = 0;
cin >> usun;
int znajdz = 0; // potrzebny mechanizm wybierający tylko pierwszy element
for (int i = 0; i < ile; i++) {
if (usun != wskaznik[i]) // '==' pokarze wybrane, '!+' usunie wybrane
{
n_wskaznik[j] = wskaznik[i];
j++;
cout << wskaznik[i] << ",";
}
}
return 0;
}