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

ออพีเรเตอร์ multimap::operator= ใน C++ STL

Multimap ใน C++ STL คืออะไร?

Multimap เป็น associative container ที่คล้ายกับ map แต่อนุญาตให้มีหลายค่าผูกกับคีย์เดียวกันได้ ข้อมูลจัดเรียงอัตโนมัติตามคีย์

ออพีเรเตอร์ multimap::operator= คืออะไร?

ออพีเรเตอร์ operator= (assignment operator) ใช้สำหรับ คัดลอก (copy) เนื้อหาจาก multimap ตัวหนึ่งไปยังอีกตัวหนึ่ง โดยจะ ทับซ้อน (overwrite) เนื้อหาเดิมของ multimap ด้านซ้ายทั้งหมด

รูปแบบไวยากรณ์ (Syntax)

multiMap_name1 = multimap_name2;

พารามิเตอร์

ด้านซ้าย: multimap ปลายทาง (destination) ที่จะรับข้อมูล
ด้านขวา: multimap ต้นทาง (source) ที่จะคัดลอกข้อมูลมา

ค่าที่ส่งคืน (Return Value)

คืนค่า reference ไปยัง multimap ด้านซ้าย (*this) เพื่อรองรับ chaining assignment

ตัวอย่างการใช้งาน

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

int main() {
    multimap<int, char> mul_1;
    multimap<int, char> mul_2;
    multimap<int, char>::iterator i;
    
    // แทรกข้อมูลเข้า multimap1
    mul_1.insert(make_pair(0, 'a'));
    mul_1.insert(make_pair(1, 'b'));
    mul_1.insert(make_pair(2, 'c'));
    mul_1.insert(make_pair(3, 'd'));
    
    // แทรกข้อมูลเข้า multimap2
    mul_2.insert(make_pair(4, 'e'));
    mul_2.insert(make_pair(5, 'f'));
    mul_2.insert(make_pair(6, 'g'));
    
    // เรียก operator= คัดลอก mul_2 -> mul_1
    mul_1 = mul_2;
    
    // แสดงข้อมูล multimap1 หลัง copy
    cout << "Elements in multimap1 are: " << "\n";
    for (i = mul_1.begin(); i != mul_1.end(); i++) {
        cout << (*i).first << " " << (*i).second << "\n";
    }
    
    // แสดงข้อมูล multimap2 (ไม่เปลี่ยนแปลง)
    cout << "\nElements in multimap2 are: " << "\n";
    for (i = mul_2.begin(); i != mul_2.end(); i++) {
        cout << (*i).first << " " << (*i).second << "\n";
    }
    
    return 0;
}

ผลลัพธ์

Elements in multimap1 are:
4 e
5 f
6 g

Elements in multimap2 are:
4 e
5 f
6 g

คุณสมบัติสำคัญ

  • Deep copy - สร้างสำเนาของทุกองค์ประกอบ ไม่ได้ share memory
  • Exception safety - Strong exception guarantee (หาก throw exception mul_1 จะคงสภาพเดิม)
  • Time complexity - O(n) โดย n คือจำนวนองค์ประกอบใน source
  • Allocator propagation - ตามกฎของ allocator_traits (C++11 ขึ้นไป)

Copy Assignment vs Move Assignment (C++11)

// Copy assignment (คัดลอก)
mul_1 = mul_2;

// Move assignment (ย้าย - mul_2 จะว่างหลังนี้)
mul_1 = std::move(mul_2);

สรุป

operator= ให้การ copy assignment semantics มาตรฐานสำหรับ multimap ทำให้สามารถคัดลอก container ทั้งหมดได้ง่ายด้วย syntax ที่เป็นธรรมชาติ ควรพิจารณา move assignment เมื่อไม่ต้องการ source อีกต่อไป เพื่อประสิทธิภาพที่ดีกว่า