Data structures part 2 Flashcards
What is a set
Sorted in ascending order
unique values only
can add or remove but not modify
based on sorting not indexing
Create a set and print its elements
include <set></set>
set<string> cars;</string>
set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};</string>
// Print set elements
for (string car : cars) {
cout «_space;car «_space;“\n”;
}
How are sets sorted
alphabetically or numerically
1234
abcd
Sort a set in descending order
// Sort elements in a set in descending order
set<int, greater<int>> numbers = {1, 7, 3, 2, 5, 9};
// Print the elements
for (int num : numbers) {
cout << num << "\n";
}</int>
Add an element to a set
car.insert(“element”)
Remove a specific element
cars.erase(“Volvo”)
Remove all items from a set
cars.clear()
Check if a set is empty
cars.empty()
loop through a set
set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};</string>
for (string car : cars) {
cout «_space;car «_space;“\n”;
}
What is a map
Stores key:value pairs, so basically a dictionary
stored in ascending order
You will need to define the key and value data type
Create a map
include <map>
map<string, int> people = { {“John”, 32}, {“Adele”, 45}, {“Bo”, 29} };
Access the value for a key named ‘john’ in a map called ‘people’
cout «_space;people[“john”]
or cout «_space;people.at(“John”)
at is preferred
Add elements to a map
people[“Jenny”] = 22;
or
people.insert({“Jenny”, 32});
Can you have two elements with equal keys?
No, values can be equal though
Remove a specific element from a map
people.erase(“John”)
Remove all elements from a map
people.clear()
Show how many elements a map has
people.size()
Check if the map is empty
empty();
Show if the key “John” exists
people.count(“John”)
Loop through a map
Now loop through these in reverse order
map<string, int> people = { {“John”, 32}, {“Adele”, 45}, {“Bo”, 29} };
for (auto person : people) {
cout «_space;person.first «_space;” is: “ «_space;person.second «_space;“\n”;
}
auto - auto detects data type
.first - for keys
.second - for values
map<string, int, greater<string>> people = { {"John", 32}, {"Adele", 45}, {"Bo", 29} };</string>
for (auto person : people) {
cout «_space;person.first «_space;” is: “ «_space;person.second «_space;“\n”;
}