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 Overflow
Discussions

Difference of sets in C
Hi. What algorithm can I use for the difference of sets with arrays in C? More on reddit.com
🌐 r/learnprogramming
1
3
November 24, 2024
c - Can one (re)set all the values of an array in one line (after it has been initialized)? - Stack Overflow
No, C doesn't have such feature. If you are setting all array elements to the same value use memset(3). More on stackoverflow.com
🌐 stackoverflow.com
Question for Array in C (with function e.g. set_array) - CS50 Stack Exchange
Is there something wrong on cs50 IDE? or just I don't understand them yet. Please let me know anything I am missing... ... You're passing in arrays of smaller sizes into your function set_array with accepts arrays of size 4. More on cs50.stackexchange.com
🌐 cs50.stackexchange.com
March 31, 2020
arrays - How to check if "set" in c - Stack Overflow
Initialize the array to some sentinal value in all cells. ... One solution perhaps is to use a separate array of flags. When you assign one of the elements, set the flag in the boolean array. More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 2
6

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:

  1. What does the consumer need to do with the container?

  2. 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:

  • Array should be implemented as a simple slap of contiguous memory that holds (the references to) its elements. A push() 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.

  • Set is required to ensure that its elements are unique. That is, where Array.push() is happy to push an element twice, Set.insert() must somehow catch this condition and handle it. This requires extra work. To get O(1) performance, Set would 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 than Array.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.

2 of 2
2

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.

🌐
Medium
medium.com › free-code-camp › learn-your-coding-fundamentals-the-main-differences-between-sets-and-arrays-4a9ed29bfb2f
Learn your coding fundamentals: the main differences between sets and arrays | by Anthony Sistilli | We’ve moved to freeCodeCamp.org/news | Medium
July 9, 2018 - To answer that question, we have to understand the fundamental differences between a set and an array. If you are a visual learner and prefer a video explanation, here’s a 3 minute video that explains the answer (albeit in less depth). Arrays were one of the first data structures I learned how to use. Not only are they a fundamental data structure used in almost every coding application, but they’re fairly easy to understand as well.
🌐
Dot Net Tutorials
dotnettutorials.net › home › array set operations in c
Array Set Operations in C with Examples - Dot Net Tutorials
December 31, 2021 - The first array is copied to array C. How much time is taken? m time. Now, should we copy all elements of array B? We cannot blindly copy 2nd set. If any element of 2nd set is already present in array C then we have to leave that element and check for the next one.
🌐
Reddit
reddit.com › r/learnprogramming › difference of sets in c
r/learnprogramming on Reddit: Difference of sets in C
November 24, 2024 - Set difference is basically just a special case of a join operation, so you can use any join algorithm. The simple, inefficient solution is to just use a doubly-nested loop: for each element in array A, search for it in array, B, and copy it ...
🌐
Stack Exchange
cs50.stackexchange.com › questions › 36637 › question-for-array-in-c-with-function-e-g-set-array
Question for Array in C (with function e.g. set_array) - CS50 Stack Exchange
March 31, 2020 - While I was doing cs50 week2. I found something hard to understand. #include<stdio.h> void set_array(int array[4]); void set_int(int x); int main(void) { int a = 10; int b[4] = {0, 1, 2, 3}; set_int(a); set_array(b); printf("%d %d\n", a, b[0]); } void set_array(int array[4]) { array[0] = 22; } void set_int(int x) { x = 22; }
Find elsewhere
🌐
Medium
medium.com › front-end-weekly › es6-set-vs-array-what-and-when-efc055655e1a
ES6 — Set vs Array — What and when? | by Maya Shavin | Frontend Weekly | Medium
November 9, 2018 - Well, in general, Array is type of structure representing block of data (numbers, objects, etc…) allocated in consecutive memory. ... Set, more familiar as a Math concept, is an abstract data type which contains only distinct elements/objects ...
🌐
Cplusplus
cplusplus.com › doc › tutorial › arrays
Cplusplus
NOTE: The elements field within square brackets [], representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs. By default, regular arrays of local scope (for example, those declared within a function) are left uninitialized. This means that none of its elements are set to any particular value; their contents are undetermined at the point the array is declared.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › top differences tutorial › list vs set
List vs Set | Top 5 Differences and Comparisons You Should Learn
March 17, 2023 - The lists have variable size, i.e. elements can be appended in the list while arrays have fixed size. Set is an abstract data structure. Set has unique elements, and the order of elements is not important.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Top answer
1 of 4
64

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/remove functionality.

You can also use open addressing as an alternative to maintaining and managing buckets.

2 of 4
6

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.

🌐
GeeksforGeeks
geeksforgeeks.org › c++ › difference-between-stdset-vs-stdvector-in-c-stl
Difference between std::set vs std::vector in C++ STL - GeeksforGeeks
July 23, 2025 - The elements of the sets are always stored in sorted form. ... // C++ program to demonstrate the // working of set in c++ #include <bits/stdc++.h> using namespace std; // Driver Code int main() { set<int> s; // Insert elements into the set s.insert(11); s.insert(6); s.insert(12); s.insert(0); // Duplicate elements s.insert(0); cout << "Elements in set:\n"; // The inserted elements get sorted // Print the elements of the set for (auto it : s) { cout << it << " "; } return 0; }
🌐
TutorialsPoint
tutorialspoint.com › cprogramming › c_arrays.htm
Arrays in C
An array in C is a collection of data items of similar data type. One or more values same data type, which may be primary data types (int, float, char), or user-defined types such as struct or pointers can be stored in an array.
🌐
DEV Community
dev.to › david4473 › set-vs-array-14c0
Set vs Array - DEV Community
October 11, 2021 - Set stores data in collections with keys that are iterable in the order of insertion. An array on the other hand - is a global object that stores high-level list-like objects called arrays in the consecutive memory for later use.
🌐
Florida State University
cs.fsu.edu › ~myers › c++ › notes › arrays.html
Array Basics
Can we do the same for arrays? Yes, for the built-in types. Simply list the array values (literals) in set notation { } after the declaration.
Top answer
1 of 2
34

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.

2 of 2
0

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.