MAP in C++ STL

MAP in C++ STL

MAP DESCRIPTION:

  • A container that represents an associative array of key-value pairs.

  • Allows efficient retrieval of values based on their associated keys.

  • Ensures that each key is unique within the map.

  • Suitable for scenarios where a collection of key-value pairs needs to be maintained.

  • Integer value stores in increasing order and string value store Lexicographically."Lexicographically" refers to the ordering or comparison of words or sequences based on the alphabetical order of their individual characters. In other words, it is the order used in a standard dictionary.


ALL THE POSSIBLE WAY TO DECLARE, INITIALIZE AND PRINTING MAP:

using namespace std;

int main() {
    // Declaration of an empty map with keys as integers and values as strings
    map<int, string> myMap;

    // Declaration of a map with keys as doubles and values as integers
    map<double, int> doubleIntMap;

    // Declaration of a map with keys as strings and values as doubles
    map<string, double> stringDoubleMap;

    // Initializing map with values using initializer list
    map<int, string> initializedMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};

    // Dynamic initialization using insert
    map<string, int> dynamicMap;
    dynamicMap["apple"] = 5;
    dynamicMap["banana"] = 3;
    dynamicMap["orange"] = 7;

    // Copying from another map
    map<int, string> sourceMap = {{10, "Ten"}, {20, "Twenty"}, {30, "Thirty"}};
    map<int, string> copiedMap(sourceMap); // Copy constructor

    // Printing map using range-based for loop
    cout << "Initialized Map (range-based for loop): ";
    for (const auto& pair : initializedMap) {
        cout << "{" << pair.first << ": " << pair.second << "} ";
    }
    cout << endl;

    // Printing map using for loop and iterators
    cout << "Dynamic Map (iterator): ";
    for (map<string, int>::iterator it = dynamicMap.begin(); it != dynamicMap.end(); ++it) {
        cout << "{" << it->first << ": " << it->second << "} ";
    }
    cout << endl;

    // Printing map using for loop and auto keyword
    cout << "Copied Map (auto): ";
    for (const auto& pair : copiedMap) {
        cout << "{" << pair.first << ": " << pair.second << "} ";
    }
    cout << endl;

    return 0;
}

OUTPUT:

Initialized Map (range-based for loop): {1: One} {2: Two} {3: Three}
Dynamic Map (iterator): {apple: 5} {banana: 3} {orange: 7}
Copied Map (auto): {10: Ten} {20: Twenty} {30: Thirty}

MAP MEMBER FUNCTIONS:

1. Empty:

  • Works: Returns whether the map is empty.

  • Syntax:

      //Example:
      map<int, string> myMap;
      bool isEmpty = myMap.empty();
    

2. Size:

  • Works: Returns the number of elements in the map.

Syntax:

//Example:
map<int, string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
size_t mapSize = myMap.size();

CODE:

#include <iostream>
#include <map>

int main() {
    // Creating a map
    std::map<int, std::string> myMap;

    // Checking if the map is empty
    if (myMap.empty()) {
        std::cout << "Map is empty.\n";
    } else {
        std::cout << "Map is not empty.\n";
    }

    // Adding elements to the map
    myMap[1] = "One";
    myMap[2] = "Two";
    myMap[3] = "Three";

    // Getting the size of the map
    std::cout << "Size of the map: " << myMap.size() << "\n";

    // Checking if the map is empty after adding elements
    if (myMap.empty()) {
        std::cout << "Map is empty.\n";
    } else {
        std::cout << "Map is not empty.\n";
    }

    return 0;
}

OUTPUT:

Map is empty.
Size of the map: 3
Map is not empty.

MAP MODIFIERS:

1. Insert:

  • Works: Inserts a key-value pair into the map.

  • Syntax: myMap.insert({key, value})

  • Example:

      map<int, string> myMap;
      myMap.insert({1, "One"});
    

2. Erase:

  • Works: Removes the element with the specified key from the map.

  • Syntax: myMap.erase(key)

  • Example:

      map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};
      myMap.erase(2);
    

3. Clear:

  • Works: Removes all elements from the map.

  • Syntax: myMap.clear()

  • Example:

      map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};
      myMap.clear();
    

    CODE:

  •   #include <iostream>
      #include <map>
    
      using namespace std;
    
      int main() {
          // Create a map with key-value pairs of string and int
          map<string, int> myMap;
    
          // Insert key-value pairs into the map
          myMap.insert({"One", 1});
          myMap.insert({"Two", 2});
          myMap.insert({"Three", 3});
    
          // Display the initial contents of the map
          cout << "Initial Map:" << endl;
          for (auto it: myMap) {
              cout << it.first << ": " << it.second << endl;
          }
    
          // Remove an element with a specified key
          string keyToRemove = "Two";
          myMap.erase(keyToRemove);
    
          // Display the map after erasing an element
          cout << "\nMap after erasing '" << keyToRemove << "':" << endl;
         for (auto it: myMap) {
              cout << it.first << ": " << it.second << endl;
          }
    
          // Clear all elements from the map
          myMap.clear();
    
          // Display the map after clearing all elements
          cout << "\nMap after clearing all elements:" << endl;
           for (auto it: myMap) {
              cout << it.first << ": " << it.second << endl;
          }
    
          return 0;
      }
    

    OUTPUT:

Initial Map:
One: 1
Three: 3
Two: 2

Map after erasing 'Two':
One: 1
Three: 3

MAP ALGORITHM:

1. Find:

  • Works: Returns an iterator to the element with the specified key or end() if not found.

  • Syntax: myMap.find(key)

  • Example:

      map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};
      auto it = myMap.find(2);
    

2. Count:

  • Works: Returns the number of elements with the specified key (0 or 1 for map).

  • Syntax: myMap.count(key)

  • Example:

      map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};
      int occurrences = myMap.count(2);
    

3. Lower Bound:

  • Works: Returns an iterator pointing to the first element not less than the specified key.

  • Syntax: myMap.lower_bound(key)

  • Example:

      map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};
      auto it = myMap.lower_bound(2);
    

4. Upper Bound:

  • Works: Returns an iterator pointing to the first element greater than the specified key.

  • Syntax: myMap.upper_bound(key)

  • Example:

      map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};
      auto it = myMap.upper_bound(2);
    

5. Equal Range:

  • Works: Returns a pair of iterators representing the range of elements with the specified key.

  • Syntax: myMap.equal_range(key)

Example:

map<int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};
auto range = myMap.equal_range(2);

CODE:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};

    // Find
    auto itFind = myMap.find(2);
    if (itFind != myMap.end()) {
        std::cout << "Element with key 2 found: " << itFind->second << "\n";
    } else {
        std::cout << "Element with key 2 not found.\n";
    }

    // Count
    int occurrences = myMap.count(2);
    std::cout << "Number of occurrences of key 2: " << occurrences << "\n";

    // Lower Bound
    auto itLowerBound = myMap.lower_bound(2);
    std::cout << "Lower bound of key 2: " << itLowerBound->second << "\n";

    // Upper Bound
    auto itUpperBound = myMap.upper_bound(2);
    std::cout << "Upper bound of key 2: " << itUpperBound->second << "\n";

    // Equal Range
    auto range = myMap.equal_range(2);
    std::cout << "Equal range for key 2: " << range.first->second << " to " << (--range.second)->second << "\n";

    return 0;
}

OUTPUT:

Element with key 2 found: Two
Number of occurrences of key 2: 1
Lower bound of key 2: Two
Upper bound of key 2: Three
Equal range for key 2: Two to Two

MULTIMAP DESCRIPTION:

  • A container that represents an associative array of key-value pairs where multiple elements with the same key are allowed.

  • Allows multiple values to be associated with the same key.

Suitable for scenarios where a collection of key-value pairs needs to be maintained, and keys can have multiple associated values.


ALL THE POSSIBLE WAY TO DECLARE, INITIALIZE AND PRINTING MULTI_MAP:

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main() {
    // Declaration of an empty multimap with keys as integers and values as strings
    multimap<int, string> myMultimap;

    // Declaration of a multimap with keys as doubles and values as integers
    multimap<double, int> doubleIntMultimap;

    // Declaration of a multimap with keys as strings and values as doubles
    multimap<string, double> stringDoubleMultimap;

    // Initializing multimap with values using initializer list
    multimap<int, string> initializedMultimap = {{1, "One"}, {2, "Two"}, {1, "Another One"}};

    // Dynamic initialization using insert
    multimap<string, int> dynamicMultimap;
    dynamicMultimap.insert({"apple", 5});
    dynamicMultimap.insert({"banana", 3});
    dynamicMultimap.insert({"apple", 8});

    // Copying from another multimap
    multimap<int, string> sourceMultimap = {{10, "Ten"}, {20, "Twenty"}, {10, "Another Ten"}};
    multimap<int, string> copiedMultimap(sourceMultimap); // Copy constructor

    // Printing multimap using range-based for loop
    cout << "Initialized Multimap (range-based for loop): ";
    for (const auto& pair : initializedMultimap) {
        cout << "{" << pair.first << ": " << pair.second << "} ";
    }
    cout << endl;

    // Printing multimap using for loop and iterators
    cout << "Dynamic Multimap (iterator): ";
    for (multimap<string, int>::iterator it = dynamicMultimap.begin(); it != dynamicMultimap.end(); ++it) {
        cout << "{" << it->first << ": " << it->second << "} ";
    }
    cout << endl;

    // Printing multimap using for loop and auto keyword
    cout << "Copied Multimap (auto): ";
    for (const auto& pair : copiedMultimap) {
        cout << "{" << pair.first << ": " << pair.second << "} ";
    }
    cout << endl;

    return 0;
}

OUTPUT:

Initialized Multimap (range-based for loop): {1: One} {1: Another One} {2: Two}
Dynamic Multimap (iterator): {apple: 5} {apple: 8} {banana: 3}
Copied Multimap (auto): {10: Ten} {10: Another Ten} {20: Twenty}

MULTIMAP MEMBER FUNCTIONS:

1. Empty:

  • Works: Returns whether the multimap is empty.

  • Syntax: myMultimap.empty()

  • Example:

      multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};
      bool isEmpty = myMultimap.empty();
    

2. Size:

  • Works: Returns the number of elements in the multimap.

  • Syntax: myMultimap.size()

Example:

multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};
size_t multimapSize = myMultimap.size();

CODE:

#include <iostream>
#include <map>

using namespace std;

int main() {
    // Creating a multimap
    multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};

    // Empty
    bool isEmpty = myMultimap.empty();
    if (isEmpty) {
        cout << "Multimap is empty.\n";
    } else {
        cout << "Multimap is not empty.\n";
    }

    // Size
    size_t multimapSize = myMultimap.size();
    cout << "Size of the multimap: " << multimapSize << "\n";

    return 0;
}

OUTPUT:

Multimap is not empty.
Size of the multimap: 3

MULTIMAP MODIFIERS:

1. Insert:

  • Works: Inserts a key-value pair into the multimap.

  • Syntax: myMultimap.insert({key, value})

  • Example:

      multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}};
      myMultimap.insert({2, "Another Two"});
    

2. Erase:

  • Works: Removes all elements with the specified key from the multimap.

  • Syntax: myMultimap.erase(key)

  • Example:

      multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};
      myMultimap.erase(2);
    

3. Clear:

  • Works: Removes all elements from the multimap.

  • Syntax: myMultimap.clear()

Example:

multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};
myMultimap.clear();

CODE:

#include <iostream>
#include <map>

using namespace std;

int main() {
    // Creating a multimap
    multimap<int, string> myMultimap;

    // Inserting key-value pairs
    myMultimap.insert(pair<int, string>(1, "One"));
    myMultimap.insert(pair<int, string>(2, "Two"));
    myMultimap.insert(pair<int, string>(2, "Another Two"));

    // Displaying the multimap before erase
    cout << "Multimap before erase:\n";
    for (const auto& entry : myMultimap) {
        cout << entry.first << ": " << entry.second << "\n";
    }

    // Erasing elements with key 2
    myMultimap.erase(2);

    // Displaying the multimap after erase
    cout << "\nMultimap after erase:\n";
    for (const auto& entry : myMultimap) {
        cout << entry.first << ": " << entry.second << "\n";
    }

    // Clearing the multimap
    myMultimap.clear();

    // Displaying the multimap after clear
    cout << "\nMultimap after clear:\n";
    for (const auto& entry : myMultimap) {
        cout << entry.first << ": " << entry.second << "\n";
    }

    return 0;
}

OUTPUT:

Multimap before erase:
1: One
2: Two
2: Another Two

Multimap after erase:
1: One

Multimap after clear:

MULTISET ALGORITHMS:

1. Find:

  • Works: Returns an iterator to the element with the specified key or end() if not found.

  • Syntax: myMultimap.find(key)

  • Example:

      multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};
      auto it = myMultimap.find(2);
    

2. Count:

  • Works: Returns the number of elements with the specified key.

  • Syntax: myMultimap.count(key)

  • Example:

      multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};
      int occurrences = myMultimap.count(2);
    

3. Lower Bound:

  • Works: Returns an iterator pointing to the first element not less than the specified key.

  • Syntax: myMultimap.lower_bound(key)

  • Example:

      multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};
      auto it = myMultimap.lower_bound(2);
    

4. Upper Bound:

  • Works: Returns an iterator pointing to the first element greater than the specified key.

  • Syntax: myMultimap.upper_bound(key)

  • Example:

      multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};
      auto it = myMultimap.upper_bound(1);
    

5. Equal Range:

  • Works: Returns a pair of iterators representing the range of elements with the specified key.

  • Syntax: myMultimap.equal_range(key)

Example:

multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};
auto range = myMultimap.equal_range(2);

CODE:

#include <iostream>
#include <map>

using namespace std;

int main() {
    // Creating a multimap
    multimap<int, string> myMultimap = {{1, "One"}, {2, "Two"}, {2, "Another Two"}};

    // Find
    auto itFind = myMultimap.find(2);
    if (itFind != myMultimap.end()) {
        cout << "Element with key 2 found: " << itFind->second << "\n";
    } else {
        cout << "Element with key 2 not found.\n";
    }

    // Count
    int occurrences = myMultimap.count(2);
    cout << "Number of occurrences of key 2: " << occurrences << "\n";

    // Lower Bound
    auto itLowerBound = myMultimap.lower_bound(2);
    cout << "Lower bound of key 2: " << itLowerBound->second << "\n";

    // Upper Bound
    auto itUpperBound = myMultimap.upper_bound(1);
    cout << "Upper bound of key 1: " << itUpperBound->second << "\n";

    // Equal Range
    auto range = myMultimap.equal_range(2);
    cout << "Equal range for key 2:\n";
    for (auto it = range.first; it != range.second; ++it) {
        cout << it->second << "\n";
    }

    return 0;
}

OUTPUT:

Element with key 2 found: Two
Number of occurrences of key 2: 2
Lower bound of key 2: Two
Upper bound of key 1: Two
Equal range for key 2:
Two
Another Two

UNORDERED MAP DESCRIPTION:

  • A container that represents an associative array of key-value pairs where the order of elements is not defined.

  • Allows for efficient retrieval of values based on their associated keys.

  • Ensures that each key is unique within the unordered map.

  • Suitable for scenarios where a collection of key-value pairs needs to be maintained, and the order of elements is not important.


ALL THE POSSIBLE WAY TO DECLARE, INITIALIZE AND PRINTING UNORDERED MAP:

#include <iostream>
#include <unordered_map>
#include <string>

using namespace std;

int main() {
    // Declaration of an empty unordered_map with keys as integers and values as strings
    unordered_map<int, string> myUnorderedMap;

    // Declaration of an unordered_map with keys as doubles and values as integers
    unordered_map<double, int> doubleIntUnorderedMap;

    // Declaration of an unordered_map with keys as strings and values as doubles
    unordered_map<string, double> stringDoubleUnorderedMap;

    // Initializing unordered_map with values using initializer list
    unordered_map<int, string> initializedUnorderedMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};

    // Dynamic initialization using insert
    unordered_map<string, int> dynamicUnorderedMap;
    dynamicUnorderedMap["apple"] = 5;
    dynamicUnorderedMap["banana"] = 3;
    dynamicUnorderedMap["orange"] = 7;

    // Printing unordered_map using range-based for loop
    cout << "Initialized UnorderedMap (range-based for loop): ";
    for (const auto& pair : initializedUnorderedMap) {
        cout << "{" << pair.first << ": " << pair.second << "} ";
    }
    cout << endl;

    // Printing unordered_map using for loop and iterators
    cout << "Dynamic UnorderedMap (iterator): ";
    for (unordered_map<string, int>::iterator it = dynamicUnorderedMap.begin(); it != dynamicUnorderedMap.end(); ++it) {
        cout << "{" << it->first << ": " << it->second << "} ";
    }
    cout << endl;

    // Printing unordered_map using for loop and auto keyword
    cout << "Initialized UnorderedMap (auto): ";
    for (const auto& pair : initializedUnorderedMap) {
        cout << "{" << pair.first << ": " << pair.second << "} ";
    }
    cout << endl;

    return 0;
}

OUTPUT:

Initialized UnorderedMap (range-based for loop): {3: Three} {1: One} {2: Two}
Dynamic UnorderedMap (iterator): {orange: 7} {banana: 3} {apple: 5}
Initialized UnorderedMap (auto): {3: Three} {1: One} {2: Two}

UNORDERED MAP MEMBER FUNCTIONS:

1. Empty:

  • Works: Returns whether the unordered map is empty.

  • Syntax: myUnorderedMap.empty()

  • Example:

      unordered_map<int, string> myUnorderedMap;
      bool isEmpty = myUnorderedMap.empty();
    

2. Size:

  • Works: Returns the number of elements in the unordered map.

  • Syntax: myUnorderedMap.size()

Example:

unordered_map<int, string> myUnorderedMap = {{1, "One"}, {2, "Two"}};
size_t mapSize = myUnorderedMap.size();

CODE:

#include <iostream>
#include <unordered_map>

using namespace std;

int main() {
    // Creating an unordered map
    unordered_map<int, string> myUnorderedMap;

    // Empty
    bool isEmpty = myUnorderedMap.empty();
    if (isEmpty) {
        cout << "Unordered map is empty.\n";
    } else {
        cout << "Unordered map is not empty.\n";
    }

    // Size
    size_t unorderedMapSize = myUnorderedMap.size();
    cout << "Size of the unordered map: " << unorderedMapSize << "\n";

    return 0;
}

OUTPUT:

Unordered map is empty.
Size of the unordered map: 0

UNORDERED MAP MODIFIERS:

1. Insert:

  • Works: Inserts a key-value pair into the unordered map.

  • Syntax: myUnorderedMap.insert({key, value})

  • Example:

      unordered_map<int, string> myUnorderedMap;
      myUnorderedMap.insert({1, "One"});
    

2. Erase:

  • Works: Removes the element with the specified key from the unordered map.

  • Syntax: myUnorderedMap.erase(key)

  • Example:

      unordered_map<int, string> myUnorderedMap = {{1, "One"}, {2, "Two"}};
      myUnorderedMap.erase(1);
    

3. Clear:

  • Works: Removes all elements from the unordered map.

  • Syntax: myUnorderedMap.clear()

  • Example:

      unordered_map<int, string> myUnorderedMap = {{1, "One"}, {2, "Two"}};
      myUnorderedMap.clear();
    

    CODE:

  •   #include <iostream>
      #include <unordered_map>
    
      using namespace std;
    
      int main() {
          // Creating an unordered map
          unordered_map<int, string> myUnorderedMap;
    
          // Insert
          myUnorderedMap.insert({1, "One"});
          myUnorderedMap.insert({2, "Two"});
    
          // Displaying the unordered map after insert
          cout << "Unordered map after insert:\n";
          for (const auto& entry : myUnorderedMap) {
              cout << entry.first << ": " << entry.second << "\n";
          }
    
          // Erase
          myUnorderedMap.erase(1);
    
          // Displaying the unordered map after erase
          cout << "\nUnordered map after erase:\n";
          for (const auto& entry : myUnorderedMap) {
              cout << entry.first << ": " << entry.second << "\n";
          }
    
          // Clear
          myUnorderedMap.clear();
    
          // Displaying the unordered map after clear
          cout << "\nUnordered map after clear:\n";
          for (const auto& entry : myUnorderedMap) {
              cout << entry.first << ": " << entry.second << "\n";
          }
    
          return 0;
      }
    

    OUTPUT:

Unordered map after insert:
1: One
2: Two

Unordered map after erase:
2: Two

Unordered map after clear:

UNORDERED MAP ALGORITHM:

1. Find:

  • Works: Returns an iterator to the element with the specified key or end() if not found.

  • Syntax: auto it = myUnorderedMap.find(key);

  • Example:

      unordered_map<int, string> myUnorderedMap = {{1, "One"}, {2, "Two"}};
      auto it = myUnorderedMap.find(1);
      if (it != myUnorderedMap.end()) {
          // Element found, use 'it'
      } else {
          // Element not found
      }
    

2. Count:

  • Works: Returns the number of elements with the specified key (0 or 1 for unordered_map).

  • Syntax: int occurrences = myUnorderedMap.count(key);

  • Example:

      unordered_map<int, string> myUnorderedMap = {{1, "One"}, {2, "Two"}};
      int occurrences = myUnorderedMap.count(1);
      // 'occurrences' will be 1 if the key is found, 0 otherwise
    

CODE:

#include <iostream>
#include <unordered_map>

using namespace std;

int main() {
    // Creating an unordered map
    unordered_map<int, string> myUnorderedMap = {{1, "One"}, {2, "Two"}};

    // Find
    auto itFind = myUnorderedMap.find(1);
    if (itFind != myUnorderedMap.end()) {
        cout << "Element with key 1 found: " << itFind->second << "\n";
    } else {
        cout << "Element with key 1 not found.\n";
    }

    // Count
    int occurrences = myUnorderedMap.count(1);
    cout << "Number of occurrences of key 1: " << occurrences << "\n";

    return 0;
}

OUTPUT:

Element with key 1 found: One
Number of occurrences of key 1: 1

CONGRATULATIONS ! NOW YOU ARE THE MASTER OF MAP CONTAINER.

Did you find this article valuable?

Support AL NAFIS FUAD SHUVO by becoming a sponsor. Any amount is appreciated!