C++ 自定义输入迭代器:CMyistream_iterator 类实现与使用
C++ 自定义输入迭代器:CMyistream_iterator 类实现与使用
本文将介绍如何使用 C++ 自定义输入迭代器来简化输入操作。我们将通过实现一个名为 CMyistream_iterator 的类来展示其使用方法,并解释代码中涉及到的 in 和 _in 以及 & 符号的用途。
代码示例:
#include <iostream>
#include <string>
using namespace std;
template <class T>
class CMyistream_iterator
{
private:
T value;
istream& in;
public:
CMyistream_iterator(istream& _in) :in(_in) {
in >> value;
}
T operator *() {
return this->value;
}
void operator++(int) {
in >> value;
}
};
int main()
{
int t;
cin >> t;
while (t--)
{
CMyistream_iterator<int> inputInt(cin);
int n1, n2, n3;
n1 = *inputInt; //读入 n1
int tmp = *inputInt;
cout << tmp << endl;
inputInt++;
n2 = *inputInt; //读入 n2
inputInt++;
n3 = *inputInt; //读入 n3
cout << n1 << ' ' << n2 << ' ' << n3 << ' ';
CMyistream_iterator<string> inputStr(cin);
string s1, s2;
s1 = *inputStr;
inputStr++;
s2 = *inputStr;
cout << s1 << ' ' << s2 << endl;
}
return 0;
}
解释:
-
in和_in的区别:in是CMyistream_iterator类中的一个私有成员变量,用于存储输入流。_in是CMyistream_iterator类构造函数的参数,表示传入的输入流。
-
&符号的用途:- 在
CMyistream_iterator类构造函数中,我们使用了&符号来获取输入流的地址。 - 使用
&可以将输入流的地址传递给成员变量in,避免复制整个输入流,提高效率。
- 在
总结:
通过自定义输入迭代器 CMyistream_iterator,我们可以简化输入操作,使代码更加简洁易懂。使用 & 符号可以避免复制输入流,提高效率。
原文地址: https://www.cveoy.top/t/topic/nXjR 著作权归作者所有。请勿转载和采集!