dir.by  
  Поиск  
Компьютер, программы
C++
 std::map is a set of keys and values in C++ 
посмотрели 1472 раз
обновлено: 15 November 2024
std::map< Key type, Value type >


To use it, you need to add a library:
#include <map>
Important feature std::map
In std::map, you can quickly find the value by key
Examples
Create map
Add keys and values.
  C++  
#include <string>
#include <map>

int main()
{
     std::map<std::string, int> mapCityTemperature;
     // A key of type std::string
     // A value with type int

     mapCityTemperature["Berlin"] = 22;
     mapCityTemperature["Paris"] = 27;
     mapCityTemperature["Singapore"] = 32;
     mapCityTemperature["Moscow"] = 19;
}
Find value by key in map
  C++  
int temperature = mapCityTemperature["Singapore"];
// temperature = 32

temperature = mapCityTemperature["singapore"]; // No value found
// Singapore and singapore are distinguished by uppercase and uppercase letters
// temperature = 0
Check if there is a key or not
  C++  
auto pItem = mapCityTemperature.find("Hello");
// not found
if (pItem == mapCityTemperature.end())
{
}

pItem = mapCityTemperature.find("Singapore");
// Found by key
if (pItem != mapCityTemperature.end())
{
     std::string key = pItem->first;
     // key = "Singapore"

     int value = pItem->second;
     // value = 32
}

iterate over all keys and values
  C++  
for (auto pItem = mapCityTemperature.begin(); pItem != mapCityTemperature.end(); pItem++)
{
     std::string key = pItem->first;
     int value = pItem->second;

     // key = "Berlin"
     // value = 22
     // ...
}
 
← Previous topic
dynamic_cast in C++ (converting a pointer to a different type and checking validity in runtime)
 
Next topic →
Pass a function as a parameter to a function (callback) | C++
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Экскурсии по Москве Экскурсии по Москве: пешеходные, автобусные и речные прогулки на любой вкус
Анонс! Ярмарка вакансий для молодежи, работа (учащихся, которые хотели бы подработать в свободное время, а также выпускники)|||Минск, Витебск, Гомель, Гродно, Могилев, Борисов, Полоцк, Брест, Барановичи, Пинск с 13 по 17 апреля 2026
  Объявления  
  Объявления  
 
dynamic_cast in C++ (converting a pointer to a different type and checking validity in runtime)
std::map<Key, Value> is a set of keys and values in C++. An important feature of std::map is to quickly find a value by key
Pass a function as a parameter to a function (callback) | C++
OpenGL
Create a new OpenGL application on C++ | Library GLUT, Visual Studio
Creating a OpenGL app with 3D pyramid drawing and a motion camera on C++ | Visual Studio | Library glut for using OpenGL
Create a new OpenGL ES2 app on C++ in Windows | Visual Studio, Desktop application

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика