I find enum to be similar to an array,with the elements in it being numbered from 0. So what is the difference between an array and enum?
An Enum is basically a group of named constants.
It is an alternative to numbered flag parameters.
(It also doesn't have to be numbered from zero, you can specify the numbering.)
An Enum could be days of the week for example.
A Enum could departments in a company: eg SALES, BILLING, HR ...
A array is a sequence of memory locations. It is a collection. Each element in that collection is indexed by a number. So using that number you can retrieve the value stored at that location. Much like the page number in a book lets you look up the content of that page, the index on an array lets you look up the value stored at that location.
For example, if your company had numbered physical mail boxes for each department (starting from zero):
and you were creating some very simple software to let users log in to check how many letters they had uncollected,
you might choose to store them in an Array of Ints. Where the index is the mail box number, and the value is the number of letters in the box.
Then for ease of programming, you might choose define the departments as Enums (as described before) such that you could index of department name. But that would be getting more advanced.
You may be confusing Enum, with Enumerable which is a term used in some languages to describe any collection type which can be iterated though in sequence (Eg IEnumerable in C#). This term is not often used in C. It is not in anyway the same at all as Enum.
Array is a variable that can contain multiple elements with index starting from 0 whereas enum is an user defined datatype that contains a list of members for which an integer constant is assigned starting from 0. in case of enum the numbers starting from 0 are not indexes whereas in case of an array they are indexes. Also in case of enum you can assign your own constant values to the members that may or may not start from 0 and may or may not be in a sequence.
The main difference is that an array is a value and an enum is a type. And One main difference we can say that an array is a collection of other values (that is it contains other values, you can iterate through them or access individual ones by index), whereas an enum value is simply one atomic value. It doesn't contain any other values.
Both of them are totally different. Array is a value and enum is a type. array is a collection of different values whereas enum value is simply one value.
Array is used to iterate among various values using index whereas enum is assigned some atomic value and iterated so that we can easily iterate the type.
Array's value are assigned by using = operator 'eg. int a[4]={1,2,3,4}' and enum is the user defined data type and it is assigned like
enum days{sun,mon,tue,wed,thr,fri,sat}
Related
Suppose we have a structure array of up to 50 elements that will be added in turn from a buffer write function. How do I find the current number of recordings made in array if the maximum number of items has not been reached?
typedef struct
{
remoteInstructionReceived_t instruction;
uint16_t parameter;
} instructionData_type;
remoteInstructionReceived_t commandBuffer[50];
C arrays are fixed-size: there are always exactly 50 objects in your array. If your program logic requires some of them to be "inactive" (e.g. not written yet), you must keep track of such information separately. For example, you could use a size_t variable to store the number of "valid" entries in the array.
An alternative would be to designate a value of remoteInstructionReceived_t as a terminator, similarly to how 0 is used as a terminator for NUL-terminated strings. Then, you wouldn't have to track the "useful length" of the array separately, but you'd have to ensure a terminator always follows the last valid item in it.
In general, length-tracking is likely both more efficient and more maintainable. I am only mentioning the second (terminator) option out of a sense of completeness.
You can't, C doesn't have a way of knowing if a variable "has a value". All values are values, and no value is more real than any else.
The answer is that additional state, i.e. some form of counter variable, is required to hold this information. Typically you use that when inserting new records, to know where the next record should go.
Have you considered using a different data structure? You can wrap your structure to allow the creation of a linked list, for example. The deletion would be real just by freeing memory. Besides, it's more efficient for some kinds of operation, such as addin elements in the middle of the list.
I have a array of 2 element, when i try to convert it to NSOrderedSet it give me a size of only one element
LOG("\(listTwoElement.count)")
This line give me 2
LOG("\(NSOrderedSet.init(array: listTwoElement).count)")
this line give me only 1 element
Why conversion to NSOrderedSet change size of array ?
thanks for your help
A Set is an unordered list of unique elements. If you try to put the same element in a set twice you will only get one
An Array is an order list of elements that needn't be unique. You can have the same element may times in array.
A OrderedSet is a combination of both (but a subclass of neither). The items are ordered, like an array, but each element needs to be unique.
Unique element does not (just) mean that they are stored in different locations in memory, but that they are not "equal" in some fundamental sense. Equality can be defined differently for every class. Classes that want to define it, implement the isEqual: and hash method of the NSObjectProtocol. (Hashes of equal objects must be equal, hashes of unequal object do not need to be different).
Without knowing more about the element you are dealing with it is hard to say why they are being evaluated as equal when you don't expect them to be. I would start will looking at the class's implementation of the isEqual and hash.
I'm having a task in Modelica, where within a function, I want to read out values of a record (parameters) according to a given string type argument, similar to the dictionary type in Python.
For example I have a record containing coefficicents for different media, I want to read out the coefficients for methane, so my argument is the string "Methane".
Until now I solve this by presenting a second array in my coefficients-record storing the names of the media in strings. This array I parse in a for loop to match the requested media-name and then access the coefficients-array by using the found index.
This is obviously very complicated and leads to a lot of confusing code and nested for loops. Isn't there a more convenient way like the one Python presents with its dictionary type, where a string is directly linked to a value?
Thanks for the help!
There are several different alternatives you can use. I will add the pattern I like most:
model M
function index
input String[:] keys;
input String key;
output Integer i;
algorithm
i := Modelica.Math.BooleanVectors.firstTrueIndex({k == key for k in keys});
end index;
constant String[3] keys = {"A","B","C"};
Real[size(keys,1)] values = {1,2*time,3};
Real c = values[index(keys,"B")] "Coefficient";
annotation(uses(Modelica(version="3.2.1")));
end M;
The reason I like this code is because it can be made efficient by a Modelica compiler. You create a keys vector, and a corresponding data vector. The reason it is not a record is that you want the keys vector to be constant, and the values may vary over time (for a more generic dictionary than you wanted).
The compiler can then create a constant index for any constant names you want to lookup from this. This makes sorting and matching better in the compiler (since there are no unknown indexes). If there is a key you want to lookup at run-time, the code will work for this as well.
I have a data structure that supports following operations:
An item can be inserted in constant time. For that item the data structure assigns a unique positive integer.
(Clarification: assigned integer is not a function of inserted item, and user has no choice on the assigned integer. It is chosen solely by the data structure.)
Using that integer the item can be found in constant time.
Using that integer the item can be removed in constant time.
It is implemented using an array of pointers where the assigned integers are indices where the items are stored. Unused indices are chained up in linked-list fashion for constant time insertion.
What is/should be the name of such data structure?
It's an array with a "free list."
As it sounds like a hash based data structure, how about calling it "Simple Hash List".
Read more about hash list here http://en.wikipedia.org/wiki/Hash_list
I am a little new to C programming. I was writing a C program which has 3 integers to handle. I had all of them inside an array and suddenly I had a thought of why should I not use a structure.
My question here is when is the best time to use a structure and when to use an array. And is there any memory usage difference between the two in this particular case.
Any help regarding this is appriciated. Thanks!
An array is best when you want to loop through the values (which, essentially, means they're strongly related). Otherwise a structure allows you to give them meaningful names and avoids the need to document that array, e.g. myVar[1] is the name of the company and myVar[0] is its phone number, etc. as opposed to companyName, companyPhone.
The difference is about semantic information. If you want to store your information as a list where there is no semantic distinction between different members of that list, then use an array. Perhaps each member of the list represents a different value for the same thing.
If each of those integers represents something special or different, use a struct. Note the implications of using a struct, such as the fact that people expect the members to be closely related semantically.
struct has other advantages over array which can make it more powerful. For example, its ability to encapsulate multiple data types.
If you are passing this information between many functions, a structure is likely more practical (because there is no need to pass the size). It would be bad to pass an array (which decays to a pointer) and expect the callee to know how many items are in the array. Using a struct implicitly makes this part of the function contract.
In terms of size, there is no difference. A 4 byte int would typically be 4-byte aligned.
You can think of structure like an object in OOP languages, a structure ties related data into a single type and allows you to access each member of the structure using the member's name instead of array indices. If you can think of a singular name that could unify the related data then you should be using a structure.
An array can be thought of as a list of items, if the name you thought of above contains the word list or collection or is a plural, then you should be using arrays or other collection types. The primary use of arrays is to loop over it and apply the same operation to every items in the array or a range of items in the array. If you used an array but never looped over it, it's an indication that probably array may not be the best data type.
I would suggest to use an array if the different things you store are logically the same data, but different instance of this. (like a list of telephone numbers or ages). And use a struct when they mean different things (like age and size) bound together because they are related to the same thing (a person).
The size is equal, since both store 3 integers without anything else; You could actually cast the struct to an array and use it like that (although you shouldn't do that for its ugliness).
You could test that with this simple programm:
#include <stdio.h>
struct three_numbers{
int x;
int y;
int z;
};
int main(int argc, char** argv) {
int test[3];
printf("struct: %d, array: %d\n", sizeof(three_numbers), sizeof(test));
}
prints on my system:
struct: 12, array: 12
In my opinion, you should think first from the perspective of the design to decide which one to use. In your question you have mentioned that "I have three integers to handle". The point here is that how did you arrive at three integers?
Just as many others have noted, let's say you need store details of a person, first you need to think of the person as an object and then decide what all information relevant to that person you will need and then decide what data type you need to use for each of those details. What you are trying to do is that you have decided that data types first and then trying work your way up.
To just put in simple words about the difference between structure and array. Structure is a Composite Data Type (or a User defined data type) whereas array is just a collection of similar data.
Use structures to group information about a single object. Use arrays to group information about multiple objects.