For e.g. if we have an array in python arr = [1,3,4]. We can delete element in the array by just using arr.remove(element) ot arr.pop() and list will mutate and it's length will change and that element won't be there. Is there a way to do this is C ot C++?. If yes the how to do that?
4 Answers
I guess you're looking for std::vector (or other containers in the standard library).
7 Comments
C++), so I answered for C++. In C, you'll have to implement this yourself. If you want to do that, just try it and if you hit concrete problems, ask new question(s) here on SO (tagged C). If you don't know where to start, reading a book on data structures might be in order.std::vector does. (It's not really as difficult as it sounds, if you ignore the allocator business.)std::deque would be any more appropriate than std::vector. Python lists provide both random access ([]) and removal/insertion at arbitrary places. Not to mention things like l[3::3] = 3 * [ 0 ], to set every third element to 0.Arrays in C are just pointers and they don't contains an information about their length. So, C-programmer should keep not only a pointer but it's length too. Here's a snippet to erase a particular value from "C-array"
/// \return a new length
int removeFromArray( int * array, int arrayLength, int elementToRemove ) {
int i;
for ( i = 0; i < arrayLength; i++ ) {
if ( array[ i ] == elementToRemove ) {
memmove( & array[ i ], & array[ i + 1 ], arrayLength - i - 1 );
return arrayLength - 1;
}
}
return arrayLength;
}
Comments
In C++ either you can use std::list or std::vector based on your mileage
If you need to implement in C, you need to write your double-link list implementation or if you wan't to emulate std::vector, you can do so by using memcpy and array indexing
4 Comments
std::array or std::deque.collections.deque data structure, which makes me wonder...As I understand, you don't want or able to use standard library (BTW, why?).
You can look into the code of the vector template in one of STL implementations and see, how it's implemented.
The basic algorithm is simple. If you're deleting something from the middle of the array, you must shrink it after. If you're inserting into the middle - you must expand it before. Sometimes it involves memory reallocation and moving you array, by memcpy for example.
Or you can implement double-linked list as mentioned. But it won't behave like array.
[]array, or a STLarray<>?