Thursday, July 9, 2009

C++ array problem??

iam making a function to delete an element from array ,bute it'sn't working





int remove()


{


int Element_no;


cout%26lt;%26lt;"enter the value of element you want from 0 to "%26lt;%26lt;size-1%26lt;%26lt;endl;





cin%26gt;%26gt;Element_no;





for (int i=0;i%26lt;size;i++)


{


if(arr[i]==Element_no){





int temp = Element_no;


// cout%26lt;%26lt;"---------------------------";


// delete (arr+Element_no);


size--;


}





}


return 0;


}

C++ array problem??
The only way to remove (and presumably add) an element to an array in C++ is to implement your own abstract data structure/class, a linked list for example, and build your own remove() an add() procedures/methods.





Perhaps you're thinking of push() and pop() of later languages such as php and javascript, but they only work on the end positions of an array: these don't exist in C++





I don't quite agree with Cris C: your prompt, as worded above, asked for the *value* to remove, not array position; however, 'Element_no' is an ambiguous choice of variable name as it does imply position rather than value.
Reply:you can't make a function called remove(), its already a function. It's used to delete files.
Reply:Deletion of an array is not possible in C++. You can only copy the elements that you are interested in into a new array or you would have to use some STL implementation to achieve this.





Putting this in another way, say you have {1,2,3,4} in an array. If you delete the 2nd element, you will have to copy the remaining elements into a new array that has {1,3,4}.





Besides, your variable Element_no is actually standing for the array element number and not the content of the element. So, it is not correct to compare arr[i] to Element_no.


No comments:

Post a Comment