מפה C ++ מוסברת עם דוגמאות

mapהוא מיכל המאחסן אלמנטים בזוגות ערך מפתח. זה דומה לאוספים ב- Java, למערכים אסוציאטיביים ב- PHP או לאובייקטים ב- JavaScript.

להלן היתרונות העיקריים בשימוש map:

  • map מאחסן רק מפתחות ייחודיים והמפתחות עצמם מסודרים
  • מכיוון שהמפתחות כבר בסדר, חיפוש אחר אלמנט הוא מהיר מאוד
  • יש רק ערך אחד לכל מפתח

הנה דוגמה:

#include  #include  using namespace std; int main (){ map first; //initializing first['a']=10; first['b']=20; first['c']=30; first['d']=40; map::iterator it; for(it=first.begin(); it!=first.end(); ++it){ cout 
    

Output:

a => 10 b => 20 c => 30 d => 40

Creating a map object

map myMap;

Insertion

Inserting data with insert member function.

myMap.insert(make_pair("earth", 1)); myMap.insert(make_pair("moon", 2));

We can also insert data in std::map using operator [] i.e.

myMap["sun"] = 3;

Accessing map elements

To access map elements, you have to create iterator for it. Here is an example as stated before.

map::iterator it; for(it=first.begin(); it!=first.end(); ++it){ cout