Kort ind C++ Standard skabelonbibliotek (STL)
โก Smart opsummering
Kort ind C++ is an associative container from the Standard Template Library that stores elements as sorted key-value pairs, where each unique key maps to one value and enables fast lookup, insertion, and ordered traversal.

Hvad er Map i C++?
In C++, a MAP is an associative container storing items in a mapped form. Each item in the map is composed of a key value and a mapped value. Two mapped values cannot share the same key values.
The key values are useful for sorting and identifying elements uniquely, while the mapped values store the content associated with each key. The two may differ in type, but the member type combines them into a pair that holds both.
Before writing any code, it helps to know why a map is often the right container to reach for.
Hvorfor bruge std::map?
Here are reasons for using a map:
- std::map stores unique keys only, in sorted order based on the chosen sorting criteria.
- It is easy and fast to search for elements using the key.
- Der er kun knyttet et element til hver nรธgle.
- std::map kan bruges som et associativt array.
- std::map is implementable using balanced binary trees.
To put these benefits to use, start with the declaration syntax.
Syntaks
For at erklรฆre std::map skal du bruge denne syntaks:
std::map<key_datatype, value_datatype>map_name;
- key_datatype angiver korttasternes datatype.
- value_datatype angiver datatypen for de vรฆrdier, der svarer til korttasterne.
- map_name er navnet pรฅ kortet.
For eksempel:
map<string, int> my_map;
We declared a map named my_map. The map will have a string as the key datatype and an integer as the values datatype.
Medlemstyper
The member functions can use the following member types as either parameters or return type:
- key_type: Key (the first parameter in the template)
- kortlagt_type: T (the second parameter in the template)
- key_compare: Compare (the third parameter in the template)
- allocator_type: Alloc (the fourth parameter in the template)
- vรฆrditype: par
- vรฆrdi_sammenlign: Indlejret funktionsklasse til sammenligning af elementer
- reference: allocator_type::reference
- const_reference: allocator_type::const_reference
- pointer: allocator_type::pointer
- const_pointer: allocator_type::const_pointer
- iterator: en tovejs iterator til vรฆrditypen
- const_iterator: en tovejs iterator til const value_type
- omvendt_iterator: en omvendt iterator
- const_reverse_iterator: en konstant omvendt iterator
- forskelstype: ptrdiff_t
- stรธrrelses Type: stรธrrelse_t
Indbyggede funktioner i std::map
std::map leveres med indbyggede funktioner. Nogle af disse omfatter:
- begynde () โ This function returns the iterator to the first item of the map.
- stรธrrelse() โ This function returns the number of items in a map.
- tom() โ This function returns a Boolean value denoting whether a map is empty.
- insert(pair(key, value)) โ This function inserts a new key-value pair into a map.
- find(val) โ This function gives the iterator to the val element if it is found. Otherwise, it returns m.end().
- erase(iterator position) โ This function deletes the item at the position pointed to by the iterator.
- slette(konst g) โ This function deletes the key-value g from a map.
- klar() โ This function deletes all items from a map.
With the functions defined, the following examples put them into action, starting with iteration.
Iteration over kortelementer
You can iterate over the map elements. We simply need to create an iterator and use it for this. For example:
Eksempel 1
#include <iostream> #include <string> #include <map> using namespace std; int main() { map<int, string> Students; Students.insert(std::pair<int, string>(200, "Alice")); Students.insert(std::pair<int, string>(201, "John")); cout << "Map size is: " << Students.size() << endl; cout << endl << "Default map Order is: " << endl; for (map<int, string>::iterator it = Students.begin(); it != Students.end(); ++it) { cout << (*it).first << ": " << (*it).second << endl; } }
Output:
Her er et skรฆrmbillede af koden:
Code Forklaring:
- Inkluder iostream-header-filen i vores kode for at bruge dens funktioner.
- Inkluder strenghovedfilen i vores kode for at bruge dens funktioner.
- Inkluder kortoverskriftsfilen i vores kode for at bruge dens funktioner.
- Inkluder std-navneomrรฅdet i vores kode for at bruge dets klasser uden at kalde det.
- Kald funktionen main(). { markerer begyndelsen af โโfunktionens brรธdtekst.
- Opret et kort med navnet Studenter, hvor nรธglerne vil vรฆre heltal, og vรฆrdierne vil vรฆre strenge.
- Indsรฆt vรฆrdier i kortet Elever. En nรธgle pรฅ 200 og en vรฆrdi af Alice vil blive indsat i kortet.
- Indsรฆt vรฆrdier i kortet Elever. En nรธgle pรฅ 201 og en vรฆrdi af John vil blive indsat i kortet.
- Use the size() function to get the size of the map named Students. This should return a 2.
- Udskriv noget tekst pรฅ konsollen.
- Brug en for-lรธkke til at oprette en iterator ved navn den for at iterere over elementerne pรฅ kortet med navnet Studenter.
- Udskriv vรฆrdierne af kortet Elever pรฅ konsollen.
- Enden af โโkroppen af โโfor-lรธkken.
- Slutningen af โโhoveddelen af โโfunktionen main().
Indsรฆttelse af data i std::map
You can enter items into std::map using the insert() function. Remember that the std::map keys must be unique.
So, it first checks whether each key is present in the map. If it is present, the entry will not be inserted, but it returns the iterator for the existing entry. If it is not present, the entry is inserted.
Funktionen har fรธlgende variationer:
- insert(pair) โ with this variation, a key-value pair is inserted into the map.
- insert(start_itr, end_itr) โ with this variation, the entries will be inserted within the range defined by start_itr and end_itr from another map.
The insert_or_assign() function works in the same way as the insert() function, but if the given key already exists in the map, its value will be modified.
Eksempel 2
#include <map> #include <iostream> using namespace std; int main() { map<int, int> m{ {1,3} , {2,4} , {3,5} }; m.insert({ 5, 6 }); m.insert({ 1, 8 }); m.insert_or_assign(1, 6); cout << "Key\tElement\n"; for (auto itr = m.begin(); itr != m.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0; }
Output:
Her er et skรฆrmbillede af koden:
Code Forklaring:
- Inkluder kortoverskriftsfilen i vores kode for at bruge dens funktioner.
- Inkluder iostream-header-filen i vores kode for at bruge dens funktioner.
- Inkluder std-navneomrรฅdet i vores kode for at bruge dets klasser uden at kalde det.
- Kald funktionen main(). { markerer begyndelsen af โโfunktionens brรธdtekst.
- Opret et kort med navnet m, hvor nรธglerne vil vรฆre heltal, og vรฆrdierne vil vรฆre heltal. Der er lavet tre indtastninger pรฅ kortet.
- Indsรฆt en ny post pรฅ kortet m. En nรธgle pรฅ 5 og en vรฆrdi pรฅ 6 vil blive indsat i kortet.
- Forsรธger at indtaste en allerede eksisterende nรธgle. Da nรธglen 1 allerede findes pรฅ kortet, vil indtastningen ikke blive foretaget.
- Using the insert_or_assign() function to insert or modify an existing entry. Since the key 1 already exists, its value will be changed to 6.
- Udskriv noget tekst pรฅ konsollen. Tegnet "\t" skaber et vandret mellemrum, mens tegnet "\n" flytter musemarkรธren til nรฆste linje.
- Brug til lรธkke for at oprette en iterator ved navn itr for at iterere over elementerne pรฅ kortet ved navn m.
- Udskriv vรฆrdierne af kortet m pรฅ konsollen. Tegnet "\t" skaber et vandret mellemrum mellem hver tast og dens tilsvarende vรฆrdi. I modsรฆtning hertil flytter tegnet "\n" musemarkรธren til nรฆste linje efter hver iteration.
- Enden af โโkroppen af โโfor-lรธkken.
- Programmet skal returnere en vรฆrdi efter vellykket afslutning.
- Slutningen af โโhoveddelen af โโfunktionen main().
Sรธgning i et kort
We can use the find() function to search for elements in a map by their keys. If the key is not found, the function returns std::map::end. Otherwise, an iterator of the searched element will be returned.
Eksempel 3
#include <iostream> #include <string> #include <map> using namespace std; int main() { map<int, string> Students; Students.insert(std::pair<int, string>(200, "Alice")); Students.insert(std::pair<int, string>(201, "John")); std::map<int, string>::iterator it = Students.find(201); if (it != Students.end()) { std::cout << endl << "Key 201 has the value: => "<< Students.find(201)->second << '\n'; } }
Output:
Her er et skรฆrmbillede af koden:
Code Forklaring:
- Inkluder iostream-header-filen i vores kode for at bruge dens funktioner uden at fรฅ fejl.
- Inkluder strenghovedfilen i vores kode for at bruge dens funktioner uden at fรฅ fejl.
- Inkluder kortoverskriftsfilen i vores kode for at bruge dens funktioner uden at fรฅ fejl.
- Inkluder std-navneomrรฅdet i vores kode for at bruge dets klasser uden at kalde det.
- Call the main() function. The { marks the beginning of the body of the main() function.
- Opret et kort med navnet Studenter, hvis nรธgler vil vรฆre heltal og vรฆrdistrenge.
- Indsรฆt vรฆrdier i kortet Elever. En nรธgle pรฅ 200 og en vรฆrdi af Alice vil blive indsat i kortet.
- Indsรฆt vรฆrdier i kortet Elever. En nรธgle pรฅ 201 og en vรฆrdi af John vil blive indsat i kortet.
- Se efter vรฆrdien forbundet med en nรธgle pรฅ 201.
- Brug en if-sรฆtning til at kontrollere, om vรฆrdien for nรธglen er fundet.
- Udskriv nรธglens vรฆrdi sammen med noget tekst pรฅ konsollen.
- Slutningen af โโbrรธdteksten i if-erklรฆringen.
- Slutningen af โโhoveddelen af โโfunktionen main().
Sletning af data fra et kort
We can use the erase() function to delete a value from a map. We simply create an iterator that points to the element to be deleted. The iterator is then passed to the erase() function.
Eksempel 4
#include <iostream> #include <string> #include <map> using namespace std; int main() { map<std::string, int> my_map; my_map.insert(std::make_pair("cow", 1)); my_map.insert(std::make_pair("cat", 2)); my_map["lion"] = 3; map<std::string, int>::iterator it = my_map.find("cat"); my_map.erase(it); for (map<string, int>::iterator it = my_map.begin(); it != my_map.end(); ++it) cout << (*it).first << ": " << (*it).second << endl; return 0; }
Output:
Her er et skรฆrmbillede af koden:
Code Forklaring:
- Inkluder iostream-header-filen i vores kode for at bruge dens funktioner.
- Inkluder strenghovedfilen i vores kode for at bruge dens funktioner.
- Inkluder kortoverskriftsfilen i vores kode for at bruge dens funktioner.
- Inkluder std-navneomrรฅdet i vores kode for at bruge dets klasser uden at kalde det.
- Call the main() function. The { marks the beginning of the body of the main() function.
- Opret et kort med navnet my_map, hvis nรธgler vil vรฆre strenge og vรฆrdier heltal.
- Indsรฆt vรฆrdier i kortet my_map. En nรธgle med ko og en vรฆrdi pรฅ 1 vil blive indsat pรฅ kortet.
- Indsรฆt vรฆrdier i kortet my_map. En nรธgle af Cat og en vรฆrdi pรฅ 2 vil blive indsat i kortet.
- Tilfรธj en vรฆrdi 3 til kortet my_map med en nรธgle fra en lรธve.
- Opret en iterator til at iterere over kortet my_map pรฅ udkig efter nรธglekatten.
- Slet det element, som iteratoren peger pรฅ.
- Use an iterator to iterate over the elements of the map my_map from the start to the end.
- Udskriv indholdet af kortet my_map pรฅ konsollen.
- Programmet skal returnere output efter vellykket afslutning.
- Slutningen af โโhoveddelen af โโfunktionen main().






