📜  C++中的运算符重载以打印矢量,地图,对,..的内容

📅  最后修改于: 2021-05-30 09:00:17             🧑  作者: Mango

运算符重载是面向对象编程的功能之一,它赋予运算符一种额外的能力,使其可以对用户定义的操作数(对象)进行操作。
我们可以在竞争性编程中特别是在调试代码时利用该功能。我们需要做的就是重载流插入运算符(请参阅本文以了解更多信息) “ <<”以打印矢量,映射,集合,对等的类。例如,

向量

// C++ program to print vector objects
// by overloading "<<" operator
#include 
#include 
using namespace std;
  
// C++ template to print vector container elements
template 
ostream& operator<<(ostream& os, const vector& v)
{
    os << "[";
    for (int i = 0; i < v.size(); ++i) {
        os << v[i];
        if (i != v.size() - 1)
            os << ", ";
    }
    os << "]\n";
    return os;
}
  
// Driver code
int main()
{
    vector vec{ 4, 2, 17, 11, 15 };
  
    // Printing the elements directly
    cout << vec;
     
    return 0;
}
Output
[4, 2, 17, 11, 15]

// C++ program to print set elements
// by overloading "<<" operator
#include 
#include 
using namespace std;
  
// C++ template to print set container elements
template 
ostream& operator<<(ostream& os, const set& v)
{
    os << "[";
    for (auto it : v) {
        os << it;
        if (it != *v.rbegin())
            os << ", ";
    }
    os << "]\n";
    return os;
}
  
// Driver code
int main()
{
    set st{ 4, 2, 17, 11, 15 };
    cout << st;
    return 0;
}
Output
[2, 4, 11, 15, 17]

地图

// C++ program to print map elements
// by overloading "<<" operator
#include 
#include 
using namespace std;
  
// C++ template to print map container elements
template 
ostream& operator<<(ostream& os, const map& v)
{
    for (auto it : v) 
        os << it.first << " : " 
           << it.second << "\n";
      
    return os;
}
  
// Driver code
int main()
{
    map mp;
    mp['b'] = 3;
    mp['d'] = 5;
    mp['a'] = 2;
  
    cout << mp;
}
Output
a : 2
b : 3
d : 5

一对

// C++ program to print pair<> class
// by overloading "<<" operator
#include 
using namespace std;
  
// C++ template to print pair<>
// class by using template
template 
ostream& operator<<(ostream& os, const pair& v)
{
    os << "(";
    os << v.first << ", " 
       << v.second << ")";
    return os;
}
  
// Driver code
int main()
{
    pair pi{ 45, 7 };
    cout << pi;
    return 0;
}
Output
(45, 7)

从上面我们可以看到,由于我们不需要写下多余的for循环print语句,因此打印或调试将变得更加容易。我们所需要做的就是在cout的插入运算符“ <<”之后编写特定的容器名称。
练习:现在让我们根据您的要求设计自己的模板,并为其他容器类添加运算符重载。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”