Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ สำหรับการใช้งาน Map ใน STL

Map เป็นคอนเทนเนอร์แบบ associative ที่จัดเก็บองค์ประกอบในรูปแบบ mapped fashion แต่ละองค์ประกอบมีคีย์ (key) และค่าที่แมป (mapped value) ไม่มีคีย์ซ้ำกันได้ (unique keys)

ฟังก์ชันที่ใช้

  • m::find() – คืน iterator ไปยังองค์ประกอบที่มีคีย์ 'b' หากพบ มิฉะนั้นคืน end
  • m::erase() – ลบคีย์ออกจาก map
  • m::equal_range() – คืนคู่ iterator ที่อ้างถึงช่วงขององค์ประกอบที่มีคีย์เทียบเท่า (ใน map จะมีสูงสุด 1 ตัว)
  • m::insert() – แทรกองค์ประกอบเข้า map container
  • m::size() – คืนจำนวนองค์ประกอบใน map container
  • m::count() – คืนจำนวนการจับคู่ขององค์ประกอบที่มีคีย์ 'a' หรือ 'f' (ใน map จะเป็น 0 หรือ 1 เท่านั้น)

โค้ดตัวอย่าง

#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";

    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

ความแตกต่างจาก Multimap: Map ไม่อนุญาตคีย์ซ้ำ insert คีย์ซ้ำจะถูกข้าม count() คืนแค่ 0 หรือ 1 equal_range() คืนช่วงที่มีขนาด 0 หรือ 1