Question:
I want to delete a record in c++?
Janiper
2008-02-25 16:46:08 UTC
If the record#1 is the same as record#2, the record#2 will be deleted.

I dont know how to use delete command
there is a line that has a name of "how to use delete command" and i wanted to put the delete command inorder the program will work

can someone teach me how to use delete command

#include
#include
#include
#include
struct student
{
char name[30];
}stud[5];

void main()
{
int i,j,cmp;
clrscr();
for(i=1;i<=3;i++)
{
printf("Enter name :");
gets(stud[i].name);
j=0;
do
{
cmp = strcmp(stud[i].name , stud[j].name);
j++;
if(cmp == 0)
{
printf("The record #%d will be deleted",i );
"how to use delete command"
j=1;
}
}while(j }clrscr();
{
gotoxy(10,2);
printf("Name");
for(i=1;i<=3;i++)
{
clrscr();
gotoxy(10,3+i);
printf("%s",stud[i].name);
}
getch();
}
}
Three answers:
Mantrid
2008-02-25 16:57:12 UTC
You can't delete from the middle of a contiguous block of memory that has been allocated like "stud[5]", you have to loop through the list starting at the one you want to delete, and copy the next element over the last.



Also, for your information this is C, not C++. If it was C++ you'd use-

std::vector Students;

to store them and-

Students.erase(i);

to erase one
2008-02-25 19:12:49 UTC
To do this, you need to learn how to use vectors for dynamic memory allocation. I know this because I had the same inquiry very recently and did some research. You need to include the file vector or vector.h (depends on the compiler). The basic way you use it is, for say an array of 5 integers, is:



vector i(5);



The two most common commands are push and pop to add an array element at the end or to delete it from the end. So:



i.pop_back(); would remove the last array element.

i.push_back(); would add an array element to the end.



To work the the actual int variables, say, array element 0:



i[0] = 10;



There's a whole bunch more you can do with vectors. I recommend hitting up google searches and maybe checking out http://www.cplusplus.com for more help on this somewhat advanced topic. Hopefully this'll set you in the right direction.



Also, to use vectors don't forget to add this command to the top, before main() is declared:



using namespace std;
iqbal
2008-02-25 20:29:45 UTC
Hi,

For deleting purposes array is an inefficient way.

How ever u can still do it.

Ur array has 5 elements and ,suppose, u want to delete 3rd element. Then u simply overwrite 4th element on 3rd and 5th element on 4th. In other words u move all element in an array one place up. Finally last array element will be free, u can add last record here.



A good way of doing it is, use a Linked List and add records in it. If u want to delete a particular record, simply remove that node. Similarly u can also add any record anywhere in the list.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...