STL-Associative Containers. Associative Containers Sequence containers : "This is item 0, this is...
-
Upload
samson-lucas -
Category
Documents
-
view
225 -
download
2
Transcript of STL-Associative Containers. Associative Containers Sequence containers : "This is item 0, this is...
STL-Associative Containers
Associative Containers
• Sequence containers :"This is item 0, this is item 1, this is item 2…“
• Associative containers :– Store items by key:
I have the word "apple"I have the word "carrot"
– No numeric index – word[0] is meaningless
Sets
• Set<T> – Stores set of items– One copy max of each value– Items stored according to < operator• Can change
Set Demo
No indexes!
• No index access:
• Always need iterators:
Other Set Tools
• find(item) returns an iterator to item– Returns end() if not found
• erase() takes value or iterator
Multiset
• Same as Set, but duplicates allowed– Also in Set library
Grouping Things
• Complex groupings deserve struct/class– Class if has behaviors– Struct – simple data
• Do we really wantlots of structs like ?
Pair
• Pair template in <utility> library• Looks like:
Pair Use
• Only has first/second• Can "construct" with initializer list
Pair Use
• Can make a vector of pairs:
• But associations not explicitly stored– No order– No easy way to look up things
Map
• Stores a sorted list of key/value pairs
Key
A
B
C
D
E
Value
Apple
Banana
Carrot
Dingo
Elf
Map
• Key used as index into list– Assigning creates record
Key
A
B
C
D
E
Value
Apple
Banana
Carrot
Dingo
Elf
Map Gotcha
• Accessing a key adds it to the Map with default value
Ways to insert:
• Insertions– Map stores pairs, multiple ways to add:
Ways to insert:
• Each key can have only one value:
Iteration:
• Use iterators just like vector– Access parts with first/second
• Map stored orderedby keys
Find/Contains
• Can find(keyType):– No find(valueType)
Erase
• Erase takes key or iterator:– Not a value
MultiMap
• To store list as value, could use map of vector:
• Can’t use [] with multimap
Multimap
• Equal_range returns pair of iterators– first : First location where we found a match– second : One past last location of match– first == second : not there