It doesn't make sense to talk about which is better array or set without understanding what you are trying to accomplish.
There's a consideration you should think about: what kind of container that the iterators are pointing at, and is that container is expected to be being updated?
For example, if you are storing iterators to a vector (doesn't matter where you put these iterators), and you update the vector, the previously store iterators are possibly invalid. Be very careful of storing iterators.
It sounds like you are caching results for speed. If you need to cache results, you might be better off using one of the unordered containers. Use the same key for your search results as you do for your cache. Don't store the iterators, just the query key and the actual result. The unordered_set has O(1) lookup time and they don't take up very much space as they hash the key and store the results.
Answer from Tim Finer on Stack OverflowIt doesn't make sense to talk about which is better array or set without understanding what you are trying to accomplish.
There's a consideration you should think about: what kind of container that the iterators are pointing at, and is that container is expected to be being updated?
For example, if you are storing iterators to a vector (doesn't matter where you put these iterators), and you update the vector, the previously store iterators are possibly invalid. Be very careful of storing iterators.
It sounds like you are caching results for speed. If you need to cache results, you might be better off using one of the unordered containers. Use the same key for your search results as you do for your cache. Don't store the iterators, just the query key and the actual result. The unordered_set has O(1) lookup time and they don't take up very much space as they hash the key and store the results.
Set contains only unique objects http://en.cppreference.com/w/cpp/container/set
Difference of sets in C
c - Can one (re)set all the values of an array in one line (after it has been initialized)? - Stack Overflow
Question for Array in C (with function e.g. set_array) - CS50 Stack Exchange
arrays - How to check if "set" in c - Stack Overflow
The use of either Array or Set by your function is equivalent: You create a container, and you push stuff into it. This leaves two areas for consideration:
What does the consumer need to do with the container?
Which container is more efficient (space or time)?
If you find that the consumer just iterates over the container, both Array and Set are equivalent again from this usage perspective. However, if your user needs to answer the question "is this index in the container?", then Set is the only appropriate container type.
Once you have asserted that the container type is indeed irrelevant to use, both on the producer and consumer side, go for the more efficient container:
Arrayshould be implemented as a simple slap of contiguous memory that holds (the references to) its elements. Apush()generally means 1) checking for space (one comparison), 2) appending the new element to the end of the buffer, and 3) updating the length field.Setis required to ensure that its elements are unique. That is, whereArray.push()is happy to push an element twice,Set.insert()must somehow catch this condition and handle it. This requires extra work. To getO(1)performance,Setwould normally be implemented as a hash table. Hash tables are fast, but they are definitely more complex than a simple, contiguous buffer. Thus,Set.insert()will generally have to do significantly more work thanArray.push(), and its data structures are very likely to consume more memory.
Both space and time efficiency are better for Array than for Set. And this is why I would default to using Array over Set whenever their use is equivalent.
From what you have shown in your question, it does not matter (and consider to refactor your code in case it starts to matter).
not limited to this case, if I found both Array and Set can finish my task, should I use Array or Set
Producing an Array or a Set is typically not an end in itself, it is a means to an end, so often you can find out what the caller of your method which produces this result might prefer.
Note, if you start using an array, and it turns out for further processing a Set would be beneficial (or you need both, the array and the set representation), you can easily convert it:
let resultSet = new Set(results)
I am not a Javascript expert, but I would expect the conversion the other way round to require at a little bit more code. Thus, if in doubt, I personally would start with an array first, and switch to a set if it fits better, but that is somewhat opinionated.
memcpy(myarray, (int [5]){a,b,c,d,e}, 5*sizeof(int));
Here is a solution that is all standards compatible (C89, C99, C++)
It has the advantage that you only worry about entering the data in one place. None of the other code needs to change - there are no magic numbers. Array is declared on the heap. The data table is declared const.
(Click here to try running it in Codepad)
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned int i = 0;
int *myarray = 0;
static const int MYDATA[] = {11, 22, 33, 44, 55};
myarray = (int*)malloc(sizeof(MYDATA));
memcpy(myarray, MYDATA, sizeof(MYDATA));
for(i = 0; i < sizeof(MYDATA)/sizeof(*MYDATA); ++i)
{
printf("%i\n", myarray[i]);
}
free(myarray);
return 0;
}
There isn't things like this in C. A static array's content is always "set". You could, however, fill in some special value to pretend it is uninitialized, e.g.
// make sure this value isn't really used.
#define UNINITIALIZED 0xcdcdcdcd
int array[5] = {UNINITIALIZED, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED};
array[0] = 7;
if (array[1] != UNINITIALIZED) {
...
You can't
There values are all undefined (thus random).
You could explicitly zero out all values to start with so you at least have a good starting point. But using magic numbers to detect if an object has been initialized is considered bad practice (but initializing variables is considered good practice).
int array[ 5 ] = {};
But if you want to explicitly check if they have been explicitly set (without using magic numbers) since creation you need to store that information in another structure.
int array[ 5 ] = {}; // Init all to 0
int isSet[ 5 ] = {}; // Init all to 0 (false)
int getVal(int index) {return array[index];}
int isSet(int index) {return isSet[index];}
void setVal(int index,int val) {array[index] = val; isSet[index] = 1; }
There are multiple ways of implementing set (and map) functionality, for example:
- tree-based approach (ordered traversal)
- hash-based approach (unordered traversal)
Since you mentioned value-indexed arrays, let's try the hash-based approach which builds naturally on top of the value-indexed array technique.
Beware of the advantages and disadvantages of hash-based vs. tree-based approaches.
You can design a hash-set (a special case of hash-tables) of pointers to hashable PODs, with chaining, internally represented as a fixed-size array of buckets of hashables, where:
- all hashables in a bucket have the same hash value
- a bucket can be implemented as a dynamic array or linked list of hashables
- a hashable's hash value is used to index into the array of buckets (hash-value-indexed array)
- one or more of the hashables contained in the hash-set could be (a pointer to) another hash-set, or even to the hash-set itself (i.e. self-inclusion is possible)
With large amounts of memory at your disposal, you can size your array of buckets generously and, in combination with a good hash method, drastically reduce the probability of collision, achieving virtually constant-time performance.
You would have to implement:
- the hash function for the type being hashed
- an equality function for the type being used to test whether two hashables are equal or not
- the hash-set
contains/insert/removefunctionality.
You can also use open addressing as an alternative to maintaining and managing buckets.
Sets are usually implemented as some variety of a binary tree. Red black trees have good worst case performance.
These can also be used to build an map to allow key / value lookups.
This approach requires some sort of ordering on the elements of the set and the key values in a map.
I'm not sure how you would manage a set that could possibly contain itself using binary trees if you limit set membership to well defined types in C ... comparison between such constructs could be problematic. You could do it easily enough in C++, though.
If you're setting the array to all 0's, or if the array is an array of bytes, you can use memset
// Set myArray to all 0's
memset(myArray, 0, numberOfElementsInMyArray * sizeof(myArray[0]));
If you need to set it to something other than 0 in units larger than a byte (e.g. set an array of ints to 1's), then there is no standard function to do that -- you'll have to write your own for loop for that.
You can set it to the same value, but only to 0
How to initialize all members of an array to the same value?
initialize all elements to 0:
int myArray[10] = { 0 }; // all elements 0
There is an answer in that page for gcc as well.
They are very different.
Array
- An array is an ordered list of objects.
- An array value can be accessed by referencing its integer position in the list (zero-indexed):
a[3]references the 4th object in the array. - There is no restriction on what the values can be—duplicate values are allowed in arrays.
- An array has an object literal notation:
[1, 'apple', String, 1, :banana](this creates and initializes a new Array). - Arrays are built in to the core ruby library.
Set
- A set is an unordered pool of unique objects.
- Since it's unordered, there is no integer index you can use to access specific elements of a set.
- The uniqueness restriction means you can't have more than one copy of a value in the set.
Setis not part of the core, but part of the standard library, and thus needs arequire 'set'.- Before Ruby 2.4, there was no object literal notation for sets, you had to create them via
Set.new.- For Ruby >= 2.4.0 you can use
Set[](e.g.Set[1,2,3])
- For Ruby >= 2.4.0 you can use
For me the main difference is that Sets are implemented as hashes, so you have O(1) membership tests for elements.
Every value in a set has to be unique, but in Array you can push same value as many times as you'd like.
"Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
Removing values, interestingly enough, when dealing with small amounts of data, there isn't much performance difference between the two (Array and Set), but when you start to deal with big data, removal is a lot faster in Sets vs Arrays.
Adding values to Array is 4 times faster than adding them to set.
Iterating through the values Array is here also better performer (Growing exponentially based on the amount of data).
You can read more about the performance differences at; Javascript Set vs. Array performance
"At 10k elements, both tests ran comparable times (array: 16.6 ms, set: 20.7 ms) but when dealing with 100k elements, the set was the clear winner (array: 1974.8 ms, set: 83.6 ms) but only because of the removing operation. Otherwise the array was faster. I couldn't say exactly why that is."
Count unique items in object Set Vs Object write-up https://github.com/anvaka/set-vs-object
TL:DR Set is almost two times faster than Object.
Why Set was introduced (My guess)?
There are sometimes when you need an easy way to build up a collection of values and you have to make sure each value is unique. This brings a lot overhead away from the old fashioned check if array has the value or not and then push or skip.
This scenario was not covered in the performance post I linked earlier, but doing fast experiment on Array of 10,000 items and then adding 15 items where 5 were duplicates to the combined collection, adding to array with checking for duplicate values and skipping if duplicate it took 74ms and with set just using the set.add(value) it took 9ms.
When would you need this?
One real life example that came to my mind is that if you have an email marketing letter and you for example would have options; - TV - Music - Movies - Sports
One day your client or you would like to have only one email option for TV, Music and Movies called "Entertainment". You would need to build up a new collection based on the data from these 3 different values and you would need to make sure each email are added to the new entertainment emailing list only once. Meaning that users could've opted-in for Movies as well as TV if they are interested in both.
Here you could just make set Entertainment and then iterate through all the lists TV/Music/Movies and use Entertainment.add(email) and the set would take care of skipping values that already exists in the list. Hence avoiding duplicate emails in the emailing list.
Also set would be optimal format to store your email subscriber addresses, as nobody could accidentally opt-in twice for you emails.
Basically, set is used to store elements uniquely whereas in arrays, you can duplicate the elements. And regarding objects, in use cases when you also need to store additional information regarding each element, then you would choose object over set and array.
For example: storing info. of your apps users, which include their name, phone no., address, email etc. Then in objects, you can define a key, let's say email (or you could also create a unique id), then keys in your object would be email (or the other one) and the additional info about the user would get stored as properties.