【发布时间】:2011-11-15 10:30:51
【问题描述】:
我有一个数据文件,它是单行,由一系列嵌套的双精度组成,例如。
[[0.127279,0.763675,0.636396],[0.254558,0.890955,0.636396],
[0.127279,0.636396,0.763675],[0.254558,0.763675,0.763675],
[0.381838,0.890955,0.763675],[0.127279,0.509117,0.890955],
[0.254558,0.636396,0.890955],[0.509117,0.890955,0.890955]]
我希望能够使用跨 A 的内部类型模板化的流运算符将其读入 STL vector<vector<double> >:
vector<vector<double> > A;
FIN >> A;
当向量没有嵌套时,我已经找到了一种方法,即。一个简单的vector<T> 这样:
template <class T>
istream& operator>>(istream& s, vector<T> &A){
T x;
string token; char blank;
s >> blank; // Gobble the first '['
while( getline(s, token, ',') ) {
istringstream input(token);
input >> x;
A.push_back(x);
}
s >> blank; // Gobble the last ']'
return s;
}
但我对istream& operator>>(istream& s, vector<vector<T> >&A) 部分有疑问,因为我似乎无法正确捕捉到内部]。我确信 Boost 有办法做到这一点,但我希望看到 STL 的解决方案用于教学目的。
注意:我知道为vector<T> 重载流运算符可能会产生深远的不良后果,并且实现应该包含在它自己的类中 - 我使用上面的这个例子是为了澄清问题。
编辑: 我希望该方法足够健壮,可以处理一个输入数组,其大小(和内部数组)的大小事先不知道,而是从读取流中推断出来的。
【问题讨论】:
标签: c++ templates stream operator-overloading