gpt4 book ai didi

c++ - 嵌套模板 C++ STL 的重载流运算符

转载 作者:搜寻专家 更新时间:2023-10-31 01:18:14 25 4
gpt4 key购买 nike

我有一个数据文件,它是单行,由一系列嵌套的 double 组成,例如。

[[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]]

我希望能够将其读入 STL vector<vector<double> >使用在 A 的内部类型中模板化的流运算符:

vector<vector<double> > A;
FIN >> A;

我已经想出了一种方法来在 vector 未嵌套时执行此操作,即。一个简单的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> 重载流运算符可能会产生深远的不良后果,并且实现应该包含在它自己的类中 - 我使用上面的这个例子是为了澄清这个问题。

编辑:我希望该方法足够健壮,能够处理其大小(和内部数组)大小是事先不知道,但从读取流中推断出来的输入数组。

最佳答案

实际上,当 T 时,您的代码存在问题,您希望对两者使用相同的函数。是:

  • vector<double>
  • double

但是需要将数据读入vectordouble 的逻辑略有不同。所以你不能这样做,至少不能用这个简单的逻辑:

我宁愿写两个函数,分别处理这两种情况。毕竟,即使在您的情况下,编译器也会为 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;
}

template <class T>
istream& operator>>(istream& s, vector<vector<T>> &A)
{
vector<T> x;
string token;
char blank;

s >> blank; // Gobble the first '['
while( getline(s, token, ']') )
{
istringstream input(token);
input >> x;
s >> blank; //read , after [...]
A.push_back(x);
x.clear();
}
s >> blank; // Gobble the last ']'
return s;
}

测试代码:

int main() {
vector<vector<double>> A;
cin >> A;
for(size_t i = 0 ;i < A.size(); ++i)
{
for(size_t j = 0 ; j < A[i].size(); ++j)
cout << A[i][j] <<" ";
cout << endl;
}
return 0;
}

输入:

[[1,2,3],[4,5,6],
[7,8,9],[10,11,12],
[13,14,15],[16,17,18],
[19,20,21],[22,23,24]]

输出:

1   2   3   
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21
22 23 24

在线演示:http://ideone.com/iBbmw

关于c++ - 嵌套模板 C++ STL 的重载流运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7389930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com