Is there any way to go about deleting a single item from an array, without altering the other iems?
Is there any way to go about deleting a single item from an array, without altering the other iems?
In a standard array like this
You could create a new array and copy the items that you want to it and delete the old array.Code:int Array[10];
You could always do something like this:
I'm sure you can figure out how to apply a function to the second part. I just whipped up some really really quick code.Code:// Init new array (5 elements) int *pnArray = (int*)calloc(5, sizeof(int)); for (int i = 0; i < 5; i++) pnArray[i] = i; // Array now: {0, 1, 2, 3, 4} // Delete element ... 2 (value = 1) int *pTempArr = (int*)calloc(4, sizeof(int)); int added = 0; for (int i = 0; i < 5; i++) { if (i != 2) { pTempArr[added++] = pnArray[i]; } } free(pnArray); pnArray = pTempArr; // Copies pointer. NOTE: Don't foget to free later! (free either, points to same data)
hmm, well, I'm not too familiar with pointers right now, any other way to do it?
The answer to your question is no! There is no way to delete an element from an array. You must create a second array and copy all the elements minus the one(s) you want to delete. All of the standard containers allow you to delete elements. I would suggest vector or deque.
ok, I'll have to look up a few more things then, thnx for the help fellas
I've looked through and have started to use vectors instead of arrays, but how would I go about adding a value to a certain element of a structure through an element. I know that with an array I can type in
But how would I go about it with a vector?Code:cin >> file[n].custname;
vectors are LIFO (last in first out) data structures, therefore you need to push and pop your data into the vector, i.e.
these functions push 'A' to the top of the stack (vector), and 'pop()' pops off the top element in the stack (vector). There are many different things you can do with a vector, such as sort, search etc though im not sure on their syntax as i havent used vectors all that much. If anyone could correct me please do, i dont want to hand out bad adviceCode:file.push('A') file.pop()
>>how would I go about adding a value to a certain element of a structure through an element. I know that with an array I can type in
cin >> file[n].custname;
The syntax is exactly the same for vectors. Assuming file is the name of a vector of structs/classes and the struct/class contain custname as a member with public access, the above syntax should work
>>vectors are LIFO (last in first out) data structures, therefore you need to push and pop your data into the vector,
This is wrong. Vectors allow random access with random insertion/deletion(erasures). Stacks are LIFO, queues are FIFO, deques can add or remove at either end, and lists/vectors are random insertion/deletion. It may be more efficient to add/remove from front/back using a vector/list, but it isn't necessary.
You're only born perfect.