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
}
...
Here is a matrix declared as pointer to an array of pointers to rows.
(source: Numerical Recipes in C)
What is the better way to pass this matrix to a function along with its dimensions?
void printMatrix(float **matrix, int rows, int cols);
Or pack it in a struct
struct Matrix {
int rows, cols;
int **data;
};
and pass a pointer to the struct?
void printMatrix(struct Matrix *m);
Both ways work, however, the approach using a struct is a bit "easier" to use. You (or whoever will use this) won't have to worry about passing the correct size as well and it isn't required to organize it at all. You just handle one struct or one logical object. If you split everything up, you'll have to handle the data as well as the meta data yourself (i.e. storying/passing data and dimensions).
Is there a downside using the struct? Not that I know of (other than having to handle one more pointer). However there is one huge advantage: Using the struct you could use a function wanting data and meta data separated as well (by passing the struct elements rather than a pointer to the struct). This isn't that easy the other way around.
As for "is it worth it?" considering "should I do it for organisaiton?": Do it, if the grouping is logical. Lots of windows APIs work with structs that way, but I'm not a real fan of them, if the grouping isn't logical or it creates additional "pains". In other words: Don't group your parameters into a struct, if they're not related or if the user most likely wouldn't have them in that form (i.e. they're grouped for this call only).
Edit:
As an example:
I'd group your example data, as width and height belong to the matrix data and they're related (plus they might be used in other functions the same way).
However, I wouldn't group parameters such as this: write_log(LOG_INFO, "All data has been processed"); Adding a struct here would add complexity that isn't required. It's very likely that this group of data won't be used elsewhere and makes calling the function more complicated (as you'll have to create the struct first).
For the sake of optimization, I would consider simply passing the struct by value. i.e.
void printMatrix(struct Matrix m);
without the pointer. It's a very small data structure and the processor might just store this top-level data in the cache. The compiler and processor may be able to optimize access to this top-level data.
Then again, it might do nothing or even make it worse. Optimization can be a black art.
(And don't forget that if you make changes to the top-level Matrix struct, then you'll need to return it somehow). So maybe this should only be considered in place of const struct Matrix *m.
There is no single perfect method. In the appropriate chapter of c-faq you can see 5 methods and their comparison.
Hello I have started writing common data structure library in C similar to STL.
Here is the link . http://code.google.com/p/cstl/
I struggled a lot of whether to go ahead with having void* as basic element for data structure. and End up with structure which has two elements
typedef struct __c_lib__object {
void* raw_data;
size_t size;
} clib_object, *clib_object_ptr;
This approach allow me to store each element, but it requires lot of memory allocation , during saving and returning back the element from the container.
Can anybody please review this , and let me know if there is any other approach.
Thanks
Avinash
Names starting with double-underscore are reserved to 'the implementation' and should be avoided in user code.
Personally, I dislike typedefs for pointers; I'd rather use clib_object *x; than clib_object_ptr x;.
Why do you need to record the size of the object?
I have never programmed in C and have not programmed in C++ for a little while and either way, I am still learning.
I am writing a program in C and am converting a MATLAB program to this C program. I have a lot of variables from MATLAB that are cartesian coordinates, X Y Z, of points. Is there a variable type I could use built into C? I need to subtract different points and also do other operations on them. Any suggestions?
Thanks,
DemiSheep
Edit:
Ok I have another question. I want to make sure this is a good idea. (But first, with stackoverflow is this how I should post more information to my post, by editing my original post? -Thanks!)
Question:
I have an object with several characteristics. Say it's a car and the car has several different parameters.
Parameters:
Position on map
Altitude (sea level?)
Start position
End Position
Can I use a struct or union (or both?) to have all these parameters inside the car "object" and update the parameters in the object like you would if it was it's own class in like C++ or Java?
Like if I want to calculate the distance the car traveled from the start position to its current position in like a Cartesian plane I could do something like:
distantTraveled = car.position - car.startPosition
Thanks,
DemiSheep
There are no built-in types that will do what you want.
You'll probably have to make your own small struct type such as the following.
typedef struct {
double x, y, z;
} coordinate;
If you're limited to C (rather than C++), you'll then need to build up a small library of functions to operate on these data types.
For what it's worth, I highly recommend looking around to find a library that will provide this type of thing for you. Ideally something specialized to the domain you're working in.
You would use a struct (typedef struct {double x,y,z;} point;) or an array (double p[3]).
If you want to get more clever you could use both by employing a union:
typedef union {
struct {double x,y,z;} s;
double a[3];
} point;
but this comes at the cost of wordier access syntax:
point p;
p.a[2] = 7;
p.s.x = 5;
I'd like a C library that can serialize my data structures to disk, and then load them again later. It should accept arbitrarily nested structures, possibly with circular references.
I presume that this tool would need a configuration file describing my data structures. The library is allowed to use code generation, although I'm fairly sure it's possible to do this without it.
Note I'm not interested in data portability. I'd like to use it as a cache, so I can rely on the environment not changing.
Thanks.
Results
Someone suggested Tpl which is an awesome library, but I believe that it does not do arbitrary object graphs, such as a tree of Nodes that each contain two other Nodes.
Another candidate is Eet, which is a project of the Enlightenment window manager. Looks interesting but, again, seems not to have the ability to serialize nested structures.
Check out tpl. From the overview:
Tpl is a library for serializing C
data. The data is stored in its
natural binary form. The API is small
and tries to stay "out of the way".
Compared to using XML, tpl is faster
and easier to use in C programs. Tpl
can serialize many C data types,
including structures.
I know you're asking for a library. If you can't find one (::boggle::, you'd think this was a solved problem!), here is an outline for a solution:
You should be able to write a code generator[1] to serialize trees/graphs without (run-time) pre-processing fairly simply.
You'll need to parse the node structure (typedef handling?), and write the included data values in a straight ahead fashion, but treat the pointers with some care.
For pointer to other objects (i.e. char *name;) which you know are singly referenced, you can serialize the target data directly.
For objects that might be multiply refernced and for other nodes of your tree you'll have to represent the pointer structure. Each object gets assigned a serialization number, which is what is written out in-place of the pointer. Maintain a translation structure between current memory position and serialization number. On encountering a pointer, see if it is already assigned a number, if not, give it one and queue that object up for serialization.
Reading back also requires a node-#/memory-location translation step, and might be easier to do in two passes: regenerate the nodes with the node numbers in the pointer slots (bad pointer, be warned) to find out where each node gets put, then walk the structure again fixing the pointers.
I don't know anything about tpl, but you might be able to piggy-back on it.
The on-disk/network format should probably be framed with some type information. You'll need a name-mangling scheme.
[1] ROOT uses this mechanism to provide very flexible serialization support in C++.
Late addition: It occurs to me that this is not always as easy as I implied above. Consider the following (contrived and badly designed) declaration:
enum {
mask_none = 0x00,
mask_something = 0x01,
mask_another = 0x02,
/* ... */
mask_all = 0xff
};
typedef struct mask_map {
int mask_val;
char *mask_name;
} mask_map_t;
mask_map_t mask_list[] = {
{mask_something, "mask_something"},
{mask_another, "mask_another"},
/* ... */
};
struct saved_setup {
char* name;
/* various configuration data */
char* mask_name;
/* ... */
};
and assume that we initalize out struct saved_setup items so that mask_name points at mask_list[foo].mask_name.
When we go to serialize the data, what do we do with struct saved_setup.mask_name?
You will need to take care in designing your data structures and/or bring some case-specific intelligence to the serialization process.
This is my solution. It uses my own implementation of malloc, free and mmap, munmap system calls. Follow the given example codes. Ref: http://amscata.blogspot.com/2013/02/serialize-your-memory.html
In my approach I create a char array as my own RAM space. Then there are functions for allocate the memory and free them. After creating the data structure, by using mmap, I write the char array to a file.
Whenever you want to load it back to the memory there is a function which used munmap to put the data structure again to the char array. Since it has virtual addresses for your pointers, you can re use your data structure. That means, you can create data structure, save it, load it, again edit it, and save it again.
You can take a look on eet. A library of the enlightenment project to store C data types (including nested structures). Although nearly all libs of the enlightenment project are in pre-alpha state, eet is already released. I'm not sure, however, if it can handle circular references. Probably not.
http://s11n.net/c11n/
HTH
you should checkout gwlib. the serializer/deserializer is extensive. and there are extensive tests available to look at. http://gwlib.com/
I'm assuming you are talking about storing a graph structure, if not then disregard...
If your storing a graph, I personally think the best idea would be implementing a function that converts your graph into an adjacency matrix. You can then make a function that converts an adjacency matrix to your graph data structure.
This has three benefits (that may or may not matter in your application):
adjacency matrix are a very natural way to create and store a graph
You can create an adjacency matrix and import them into your applications
You can store and read your data in a meaningful way.
I used this method during a CS project and is definitely how I would do it again.
You can read more about adjacency matrix here: http://en.wikipedia.org/wiki/Modified_adjacency_matrix
Another option is Avro C, an implementation of Apache Avro in C.
Here is an example using the Binn library (my creation):
binn *obj;
// create a new object
obj = binn_object();
// add values to it
binn_object_set_int32(obj, "id", 123);
binn_object_set_str(obj, "name", "Samsung Galaxy Charger");
binn_object_set_double(obj, "price", 12.50);
binn_object_set_blob(obj, "picture", picptr, piclen);
// send over the network
send(sock, binn_ptr(obj), binn_size(obj));
// release the buffer
binn_free(obj);
If you don't want to use strings as keys you can use a binn_map which uses integers as keys.
There is also support for lists, and all these structures can be nested:
binn *list;
// create a new list
list = binn_list();
// add values to it
binn_list_add_int32(list, 123);
binn_list_add_double(list, 2.50);
// add the list to the object
binn_object_set_list(obj, "items", list);
// or add the object to the list
binn_list_add_object(list, obj);
In theory YAML should do what you want http://code.google.com/p/yaml-cpp/
Please let me know if it works for you.