Okay. We learned about vectors a lot. They work well for many data-storage problems. But vector is not always the best choice. In lecture we learned about a lot of standard containers in c++. Today we'll go through some basic theory and examples with just a few of them.
queue, map, multiset, hash table, etc. Each is useful for its own class of problems.
Let's say that set1 and set2 are both containers of type std::set. We want to find the "union". That is, we want to find all the elements that are in at least one of the sets (so one or the other or both).
The method is straightforward, so consider this some practice with the syntax.
Let's say that set1 and set2 are both containers of type std::set. We want to find the "intersection". That is, we want to find all the elements that are in both sets.
The first solution we'll write up involves using a lot of the member functions from set (practicing syntax), and not thinking very hard about the algorithm. If we have time, we'll create a second solution uses the fact that sets are always sorted to run a little bit faster.
Write a function called same_elements, which inputs two vector<int>s, and outputs a bool. The function should return true if the vectors contain exactly the same elements (not necessarily in the same order), and return false otherwise. Repeated elements do not count. That is, if an element is repeated 10 times in one vector, and 3 times in another, then we still consider these vectors to have the same elements.
[1, 2], [2, 1]) returns truesame_elements( [1, 2, 3], [2, 1]) returns falsesame_elements( [1, 2, 1], [2, 1]) returns truesame_elements( [1, 2, 1], [2, 2, 1]) returns truesame_elements( [2, 9, 2, 1], [1, -4, 2, 1]) returns false
Now think about how to write a similar sameElements function using a set instead of a vector. Hint: it is very very easy. I can do it in one line.