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

ตัวดำเนินการโอเวอร์โหลดใน C ++ เพื่อพิมพ์เนื้อหาของเวกเตอร์ แผนที่ คู่ ..


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อทำความเข้าใจโอเปอเรเตอร์โอเวอร์โหลดใน C++ เพื่อพิมพ์เนื้อหาของเวกเตอร์ แผนที่ และการจับคู่

โอเปอเรเตอร์โอเวอร์โหลดเป็นฟังก์ชันของโอเปอเรเตอร์ที่ช่วยให้พวกเขาสามารถดำเนินการกับออบเจกต์ที่ผู้ใช้กำหนดและทำงานในลักษณะเดียวกันได้

ตัวอย่าง

เวกเตอร์

#include <iostream>
#include <vector>
using namespace std;
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v){
   os << "[";
   for (int 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;
   return 0;
}

ผลลัพธ์

[4, 2, 17, 11, 15]

แผนที่

#include <iostream>
#include <map>
using namespace std;
template <typename T, typename S>
ostream& operator<<(ostream& os, const map<T, S>& v){
   for (auto it : v)
      os << it.first << " : "
      << it.second << "\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

จับคู่

#include <iostream>
using namespace std;
template <typename T, typename S>
ostream& operator<<(ostream& os, const pair<T, S>& v){
   os << "(";
   os << v.first << ", "
   << v.second << ")";
   return os;
}
int main(){
   pair<int, int> pi{ 45, 7 };
   cout << pi;
   return 0;
}

ผลลัพธ์

(45, 7)