gpt4 book ai didi

C++ istream operator >>

转载 作者:行者123 更新时间:2023-11-28 01:01:14 27 4
gpt4 key购买 nike

我的运算符(operator)有问题>>

istream& operator>> (istream& is, Matrix& M) {

char first;

is>>first;


for(int i = 0;i<M.rows();i++) {

for(int j = 0;j<M.cols();j++) {

is>>M[i][j];
cout<<M[i][j];

}

is>>first;

}

return is;
}

我想要 istream 运算符的大小,因为我想更改 for 循环,以便它们不依赖于发送的矩阵,即您是否发送大小为 1 的矩阵和流 [1 2 3 4; 4 5 6 7; 1 2 3 4] 然后应该构造一个大小为 (3*4) 的新矩阵。这样我就可以使用赋值运算符将其分配给矩阵 M。

换句话说,流的形式是 "[ 1 2 3; 2 3 4; 4 5 6]" and ;表示新行。我想知道有多少行和列。

最佳答案

你可以像这样得到所有的行:

vector<string> rows;
string line;

is.ignore(INT_MAX, '['); // ignores all characters until it passes a [

while (std::getline(is, line, ';'))
rows.push_back(line); // put each row in rows

rows.back().erase(rows.back().find(']')); // erase the ending ]

现在你在 rows 中有了每一行字符串,然后

for (size_t i = 0; i < rows.size(); ++i) {
vector<int> items;
istringstream strstm(rows[i]);

std::copy(istream_iterator<int>(strstm), istream_iterator<int>(), back_inserter(items));

// now items is full of the entries, resize the matrix to hold items.size()
// many items and insert each one into it, or whatever
}

关于C++ istream operator >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8601369/

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