输出一个pair列表(由重载操作符创建)
C++ Printing out a list of pairs (created by overloaded operator)
只是想知道如何打印由重载赋值操作符创建的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;
}
}
相关文章:
- 重载操作符+:表达式必须是整型或无作用域枚举类型
- 重载操作符
- 如何重载操作符==外模板类使用友元函数
- 重载*操作符,使其在左右两边都工作
- 重载操作符<对于非随机迭代器
- 在c++中重载操作符的时间和原因
- 如何在c++中重载=操作符来通过引用进行复制
- 如何在c++中获取定义为友元的重载操作符的地址
- 使用重载操作符的文件操作表达式没有给出预期的结果
- 重载操作符()
- 重载操作符()并在类内使用
- 类中的重载操作符+
- 定时使用重载操作符
- c++带类的重载操作符
- 用列表容器重载[]操作符
- 重载操作符=
- 任何重载操作符()的静态检测
- 重载操作符以处理类对象
- 在使用另一个类的类中重载操作符==
- 派生类和基类中的重载操作符不同