我试图在 1 条单行上输入未定义数量的坐标 (x,y,weight)。示例:
Please enter all the coords:
(1,2,5) (1,5,7) (2,5,2) (2,4,4) (2,3,5) (3,4,1) (4,5,9)
我会将它们存放在一个二维数组中,所以对于我的第一个坐标,它会是这样的:
array[1][2] = 5
如果每行只有一个坐标,我会这样做:
cin >> trash_char >> x >> y >> weight >> trash_char;
array[x][y] = weight
如何在单行上处理不确定数量的坐标?
谢谢大家!
最佳答案
定义一个结构。
struct Coord3D{
float x,y,z;
};
定义一个插入运算符
template<typename ReadFunc>
istream& operator >> (istream& stream, Coord3D& coord){
return ReaderFunc(stream, coord );
}
定义一个阅读器函数。
istream& MyCoordReader(istream& stream, Coord3D& coord){
char trash_char = 0;
return stream >> trash_char >> x >> y >> weight >> trash_char;
}
像这样使用它
//template instantiation, probably wrong syntax
template<MyCoordReader> istream& opeartor >> (istream&,Coord3D&);
int main(){
std::vector<Coord3D> coordinates;
Coord3D coord;
while( cin >> coord ){ coordinates.push_back(coord); }
return 0;
}
关于c++ - cin 一行中未定义的坐标数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11811407/