C++ 自定义输入迭代器:从标准输入读取数据
C++ 自定义输入迭代器:从标准输入读取数据
本文将介绍如何使用 C++ 模板类自定义输入迭代器,并演示如何使用该迭代器从标准输入流读取不同数据类型的值。
代码示例:
#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 是 main 函数中调用的标准输入流 cin,是一个对象,可以用来从标准输入读取数据。
- _in 是 CMyistream_iterator 类的私有成员,是一个引用,用来绑定传入的输入流对象,可以用来从输入流对象中读取数据。
总结:
本文通过自定义输入迭代器,演示了如何使用 C++ 模板类实现从标准输入流读取不同数据类型的功能,并解释了 in 和 _in 的区别。
原文地址: https://www.cveoy.top/t/topic/nXjN 著作权归作者所有。请勿转载和采集!