输出一个pair列表(由重载操作符创建)

C++ Printing out a list of pairs (created by overloaded operator)

本文关键字:重载 操作符 创建 列表 一个 输出 pair      更新时间:2023-10-16

只是想知道如何打印由重载赋值操作符创建的pair列表。

我已经尝试过的,如这里所见,是创建一个数组(例如list1[5])并给它赋值。然而,这似乎不是打印整个集合的最佳方式,比如5对数字,因为我必须使用循环分别打印每个元素。

这个项目实际上最初有链表函数,我省略了,因为我不确定它是否相关,但我怀疑它可能有必要打印出一个列表?除了手动打印出每个元素之外,我还可以做些什么,我将非常感激。

Pair.h:

#ifndef PAIR_H
#define PAIR_H
#include <iostream>
using namespace std;
class Pair
{
    friend ostream& operator<<(ostream& out, const Pair& p);
public:
    Pair( );    
    Pair(int firstValue, int secondValue);
    ~Pair( );
    void setFirst(int);
    void setSecond(int);
    int getFirst( ) const;
    int getSecond( ) const;
private:
    int first;
    int second;
};
#endif 

Pair.cpp

#include "Pair.h"
    //friend function
ostream& operator<<(ostream& out, const Pair& p)
{
    out << "(" << p.first << "," << p.second << ")";
    return out;
}
Pair::Pair( )
{ 
    first = 0;
    second = 0;
}
Pair::Pair(int firstValue, int secondValue)
{
    first = firstValue;
    second = secondValue;
}
Pair::~Pair( ){ }
void Pair::setFirst(int newValue)
{
    first = newValue;
}
int Pair::getFirst( ) const
{
    return first;
}
void Pair::setSecond(int newValue)
{
    second = newValue;
}
int Pair::getSecond( ) const
{
    return second;
}

Main.cpp

#include "Pair.h"
#include <iostream>
using namespace std;
void testPair();
int main()
{
    testPair();
    cout << endl;
    cout << endl;
    system("Pause");
    return 0;
}
void testPair()
{
    // Create your own testing cases after adding the class Pair.
    Pair list1[5], list2, list3;
    list1[1].setFirst(10);
    list1[1].setSecond(11);

    cout << "TEST: Pair <<nn";
    cout << "tList1 is: " << list1[1] << endl;
    // NOTE: Do NOT make your class Pair a template.
}

在这里,它只会打印(10,11),但是如果我要向列表中添加更多对,如果我坚持使用这种方法,我就必须手动打印所有这些。

如果你知道列表中有多少元素,你可以使用for循环来打印所有元素:

void print(Pair* pairs, unsigned int size)
{
    cout << "tList is:" << endl;
    for (unsigned int i = 0; i < size; i++)
    {
        cout << "(*pairs)[i] << endl;
    }
}