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

Operator Overloading เพื่อพิมพ์ Vector, Map, Pair ใน C++


ในบทเรียนนี้ เราจะสาธิต Operator Overloading ของ operator<< เพื่อพิมพ์ Vector, Map, Pair ได้ง่าย

Operator Overloading คืออะไร?

กำหนดพฤติกรรมของ Operator ให้ทำงานกับ User-defined Type ได้

1. Overload สำหรับ Vector

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

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    os << "[";
    for (size_t i = 0; i < v.size(); ++i) {
        os << v[i];
        if (i != v.size() - 1) os << ", ";
    }
    os << "]\n";
    return os;
}

int main() {
    vector<int> vec = {4, 2, 17, 11, 15};
    cout << vec; // [4, 2, 17, 11, 15]
    return 0;
}

2. Overload สำหรับ Map

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

template <typename K, typename V>
ostream& operator<<(ostream& os, const map<K, V>& m) {
    for (auto& [key, val] : m)
        os << key << " : " << val << "\n";
    return os;
}

int main() {
    map<char, int> mp;
    mp['b'] = 3; mp['d'] = 5; mp['a'] = 2;
    cout << mp;
    // a : 2
    // b : 3
    // d : 5
}

3. Overload สำหรับ Pair

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

template <typename T1, typename T2>
ostream& operator<<(ostream& os, const pair<T1, T2>& p) {
    os << "(" << p.first << ", " << p.second << ")";
    return os;
}

int main() {
    pair<int, int> p = {45, 7};
    cout << p; // (45, 7)
}

ผลลัพธ์

Vector: [4, 2, 17, 11, 15]
Map:
a : 2
b : 3
d : 5
Pair: (45, 7)

หมายเหตุ

ใน Production ควรใส่ใน Namespace ให้เหมาะสม หรือใช้ Library เช่น fmt แทน