কম্পিউটার টিউটোরিয়াল

C++ STL-এ Map বাস্তবায়ন: কী-ভ্যালু জোড়ার অ্যাসোসিয়েটিভ কন্টেইনার

Map একটি অ্যাসোসিয়েটিভ কন্টেইনার যা উপাদানগুলো ম্যাপড ফ্যাশনে সংরক্ষণ করে। প্রতিটি উপাদানের একটি কী (key) এবং একটি ম্যাপড ভ্যালু (mapped value) থাকে। কোনো দুটি ম্যাপড ভ্যালুর একই কী হতে পারে না — কীগুলো উনিক। উপাদানগুলো কী অনুযায়ী সর্টেড থাকে।

প্রধান ফাংশন:

  • m.find() – কী 'b' খুঁজে পেলে ইটারেটর রিটার্ন করে।
  • m.erase() – কী মান মুছে ফেলে।
  • m.equal_range() – নির্দিষ্ট কীর রেঞ্জ রিটার্ন করে (ম্যাপে শুধু ০ বা ১টি থাকে)।
  • m.insert() – ম্যাপে উপাদান যোগ করে।
  • m.size() – উপাদান সংখ্যা রিটার্ন করে।
  • m.count() – নির্দিষ্ট কীর ম্যাচ সংখ্যা রিটার্ন করে (ম্যাপে ০ বা ১)۔

উদাহরণ কোড

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<char, int> m;
    map<char, int>::iterator it;

    m.insert(pair<char, int>('a', 10));
    m.insert(pair<char, int>('b', 20));
    m.insert(pair<char, int>('c', 30));
    m.insert(pair<char, int>('d', 40));

    cout << "Size of the map: " << m.size() << endl;
    cout << "map contains:\n";
    for (it = m.begin(); it != m.end(); ++it)
        cout << (*it).first << " => " << (*it).second << '\n';

    // প্রতিটি কী যাচাই
    for (char c = 'a'; c <= 'd'; c++) {
        cout << "There are " << m.count(c) << " element(s) with key " << c << ":";
        for (it = m.equal_range(c).first; it != m.equal_range(c).second; ++it)
            cout << ' ' << (*it).second;
        cout << endl;
    }

    // কী উপস্থিতি যাচাই
    if (m.count('a'))
        cout << "The key a is present\n";
    else
        cout << "The key a is not present\n";

    if (m.count('f'))
        cout << "The key f is present\n";
    else
        cout << "The key f is not present\n";

    // 'b' কী মুছে ফেলা
    it = m.find('b');
    m.erase(it);

    cout << "Size of the map: " << m.size() << endl;
    cout << "map contains:\n";
    for (it = m.begin(); it != m.end(); ++it)
        cout << (*it).first << " => " << (*it).second << '\n';

    return 0;
}

আউটপুট

Size of the map: 4
map contains:
a => 10
b => 20
c => 30
d => 40
There are 1 element(s) with key a: 10
There are 1 element(s) with key b: 20
There are 1 element(s) with key c: 30
There are 1 element(s) with key d: 40
The key a is present
The key f is not present
Size of the map: 3
map contains:
a => 10
c => 30
d => 40

ম্যাপ ও মাল্টিম্যাপ পার্থক্য: ম্যাপে কী উনিক, মাল্টিম্যাপে একই কীতে একাধিক ভ্যালু সম্ভব। ম্যাপে operator[] দিয়ে সরাসরি অ্যাক্সেস/ইনসার্ট করা যায় (যেমন m['x'] = 100)।

  1. C++ STL-এ Set Union বাস্তবায়ন: দুটি সেটের ইউনিয়ন

  2. C++ STL-এ Set Symmetric Difference বাস্তবায়ন

  3. C++ STL-এ Set Intersection বাস্তবায়ন: দুটি সেটের অন্তঃসেট

  4. C++ STL-এ Set Difference বাস্তবায়ন: সেট বিয়োগ