I need to do a home assignment in VC++, which uses ADT to do several operations on an integer list. For now, we're not allowed to use classes, so I need to use struct.
I don't quite understand how ADTs work, so I'm not sure where to start, because all tutorials on the internet use classes, which I don't want to.
So are there any tutorials on the net that: 1. explain the concept of Abstract Data Types and 2. Provide an example of implementation (preferably in C++ and not using class, but struct instead).
I will give a try for an answer that is more what is my understanding.
What is an abstract datatype?
Always my first shot: Look at http://en.wikipedia.org/wiki/Abstract_data_type
My "practical" understanding of this is: There is some idea of an object that is defined by the object, its variables (or data) and the operations that are defined on this object.
For your case the object is a list of integers. The operations are something like insert a new integer, remove an integer, get the number of integers stored in the list and so on. When implementing this datatype you have to write this operations as functions. To provide this functions you will have to make up some structure to save the data to operate on.
Provide an example of implementation.
Well I won't do your homework so I will do some pseudocode:
struct ListElement {
int value;
type NextElement; //i leave the type to you
};
void insertBehind(ListElement &element, int newValue)//this is one way to do this
{
ListElement newElement(newValue); //create the new element (use new instead, don't want to "spoiler" the type to you)
newElement.nextElement = element.nextElement; //set the next element of this new one
element.NextElement = newElement; //set the new element
}
...
Related
I'm trying to implement a static linked list in C that holds any data type. I know that the node struct should use a void* but I also want each list to hold the same data type. That is, lists can hold any data type but every item in the list must be of the same type. I know using void* allows nodes to have any data type but how do I make it so that a list only contains items of the same type?
You can use the macro system to handle non void * lists... if you do something like:
#define LIST_OF(_type) struct node_of_##_type { \
struct node_of_##_type *prev, *next; \
_type data; \
}
then, you can declare as many list types as you want, you have only to say something like:
typedef char *string;
LIST_OF(string) *my_list = NULL;
/* will expend to something similar to:
struct node_of_string {
struct node_of_string *prev, next;
string data;
} *my_list = NULL;
*/
This is an attempt (well, too far yet to be comparable) to emulate the templates of C++. You will not have a list capable of storing anything, but a list adapted only to one type (but any type that can be typedef'd, as the type parameter must be a typename, not a type specification. And, as in C++, once you have that you have to instantiate every function using that type, to the proper type, forcing you to name it, (as functions cannot be overloaded in C) and to rewrite (by means of more macro expansions) to the actual code. Things get complicate soon, making it necessary some help from the language to use OOP techniques in C.
The problem with C is that it is a weakly typed language, this means that you can cast a Banana to a Truck and the compiler will be totally fine with that. Programmers in C are conditioned to keep this in mind and be very wary of what they are doing, that is to say it is the programmers responsibility to "think ahead" and make no such mistakes (e.g. like putting a Banana in a list of Trucks). You could work around this by adding another layer between your datatypes and the list nodes. A trust could hold a void* to the actual type together with an enum or an integer value representing the id of the data type you are trying to store in the list, you could call this a tagged node or something. The issue now becomes how to retrieve that tag or enum value. This will sadly add some boilerplate to your program, however, this might be automated using macro's.
Note that the problem you are highlighting (weak typing) is just part of the quirkiness of C. what I usually do in these situations is naming the variable holding the list accordingly and think very carefully of what I am doing with this variable.
A solution may be to, instead of using a List, use an array, this will at least produce a segmentation fault in some scenario's, but that will also be the case if you cast a Truck to a Banana and try to access fields which are out of memory range...
Hope this helps!
I have a list of flows, and each flow contains a list of requirements.
each requirement contains
id: which is the index of flow it is contained in
type: a string or enum representing the type
resourceId: an integer
instance: an integer
so if I were to represent in java, could do like
List<Flow> flowList = new ArrayList<>()
class Flow
{
int id;
List<Requirement> requirementList;
}
class Requirement
{
int flowID;
String type;
int resourceId;
int instance;
}
I am not sure how one would do this in C as C doesn't have an inbuilt type
list or classes. What would be the best way to approach such design in the C
language. Should I use arrays instead of List or use a LinkedList code library that
implements the basic functions, I can directly start using it in my code.
Any ideas on how to approach this problem.
On Linux linked lists are available out of box already, please see man 7 queue for more information. Unfortunately I cannot suggest something similar for Windows as I do not have experience.
See additionally man 3 queue for examples of usage.
Classes you mentioned can be typically converted to structures, of cource possibly with usage of pointer members for conversion of String to char *, etc.
I've use quite a bit of JavaScript so far. If you were to use an object constructor in JavaScript, you have access to the this constructor.
So my question relates to trying to use a similar concept in C. I created a struct that I want to be able to self reference:
struct Storage {
void (*delete)();
}
So if I were to allocate a Storage class:
struct Storage *myStruct = malloc(sizeof(struct Storage));
Let's say I'm trying to delete myStruct. If I have some delete function that I point to (with myStruct->delete = deleteStructure), I would like to do something like this:
myStruct.delete();
which would then free() the struct through a self referencing variable inside of said delete function. I'm wondering if there would be a way to have the delete function look like:
void deleteStructure() {
free( /* "this" or some equivalent C self-reference */ );
}
My assumption from research so far is that this is not possible since this is usually only in object oriented programming languages. If this is not possible, I'm wondering what would be the semantically correct way to do this. I'm hoping to make the usage of this delete functionality rather simplistic from a user interface perspective. The only way I understand this to work would be passing a reference to the structure like:
void deleteStructure(struct Storage *someStructure) {
free(someStructure);
}
which would then require deletion to be done as follows:
deleteStructure(myStruct);
To sum up: is there a way to make a delete function that uses self references in C, and if not, what would be the most semantically correct way to delete a structure in the most user friendly way?
No. You cannot even define a function for a struct.
struct Storage {
void (*delete)();
}
simply stores a pointer to a void function. That could be any void function and when it is being called, it has no connection to Storage whatsoever.
Also note that in your code, every instance of the struct stores one pointer to a void function. You could initialize them so that they all point to the same function, in which case you would simply waste 64 bit per instance without any real benefit. You could also make them point to completely different functions with different semantics.
As per #UnholySheep's comment, the correct semantical use of a struct with connection to a C function will follow the structure:
struct Storage {
/* Some definitions here */
}
void deleteStructure(struct Storage *someStructure) {
free( /* all inner structure allocations */ );
free(someStructure);
}
Here's more about passing structs by reference.
I was wondering if:
List<String> s = new ArrayList<String>()
is a list that uses the list methods but it's built with an ArrayList?
What is its behavior?
I cannot completely understand if I am creating a Queue or a LinkedList with this piece of code,
Queue q = new LinkedList();
An ArrayList implements the List interface. Similarly, a LinkedList implements the Queue interface. What that means is that:
ArrayList has promised that it will have all the methods it needs to
behave like a List
LinkedList has promised that it will have all the methods it needs to behave like a Queue
Because both classes fulfill those promises (they implement the interfaces), Java can treat an ArrayList like a List. Similarly, it can treat a LinkedList like a Queue.
Why would you want to do this? You might want to be able to pass any List into your code - you don't care how it's implemented. So you might have a HugeSparseList that also implements List that stores underlying objects completely differently. That doesn't matter to your code - as long as the API is the same, your code will still work.
List is the base class representing a sequence of elements. Array List is a particular implementation that uses an internal array and dynamically allocatez the space when required.
Linked list is a sequence of elements stored by using pointers pointing from one node to the following.
The two data structures are different in term of computational complexity, memory requirement and speed.
You may find more information here.
I have a C function named SetParams(...) with a variable number of arguments. This function sets up a static data structure (let us name it Data). SetParams is used with pairs of arguments, e.g. SetParams("paramA", paramA_value, "paramB", paramB_value) etc. It can also be called many times, e.g.
SetParams("paramA", paramA_value);
SetParams("paramB", paramB_value);
...
When all 'parameters' have been set, another function is called (let us name it Execute) that takes no args:
Execute();
// uses data from static 'Data' and performs error_handling and execution
I was wondering if I could structure this kind of code in a more object-oriented way. So, I would like some advice, especially for error-handling, since some pairs of args may contradict others.
The general practice for creating an object oriented design in C is for every method you have you will pass in a reference to a struct which is used to store all the classes member variables. In otherwords in C++ where you'd have listObj.clear() you have in C list_clear(&listObj).
This is kind of ugly, but it's necessary unless you want to use static member variables and limit the implementation to being used only once.
In the example below, notice how in each method a reference to a struct ParamUtilObj is passed in.
// --- paramUtil.h
// Stores all the objects member variables (public and private)
struct ParamUtilObj {
int paramCnt;
char param1[25];
char param2[25];
...
};
bool paramUtil_initialize( struct* ParamUtilObj pData );
bool paramUtil_addParam( struct* ParamUtilObj pData, const char* pKey, const char* pValue );
bool paramUtil_execute( struct* ParamUtilObj pData);
With respect to variadic methods. I'd try to avoid them if possible and just add them in one at a time. The business logic to validate the params is an entirely different topic in my opinion. I'd need more info to recommend the best approach. But... It seems to me since you're going to have to do validation such as if( MethodA ) then check for presence of some other argument... it might be easier to create several SetParam methods for each MethodType which the user could specify in the script.
I would recommend using a linked list to store your params and put all your methods as function pointers to a struct.
struct MyClass {
struct LinkedList* params;
void (*setParams)(...);
void (*execute)()
}
the linked list would be a key value pair
struct LinkedList {
struct LinkedList *next;
char * key;
char * value;
}
I dont know how you have your SetParams implemented, from the sound it just does a little bit of parsing and storing and forwards error handling downstream to the Execute call.
Since you are using variable length arguments, are you using the va_* macros? Doing so with a format string might allow you to insert the error handling into your SetParams call and allow Execute to just iterate over the values and do its thing.
Generally, if you have a function that handles setting parameters that should be where you manage errors associated with setting parameters. Errors encountered in the execution of command should be addressed in the execute function.
You cannot do it this way, because in C variadic functions don't know the number of arguments you've supplied, so you need somehow let function know it, like specifying number of params as first parameter or use printf way, when number of parameters can be found from format string.