c++ - cin 一行中未定义的坐标数

标签 c++

我试图在 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/

相关文章:

c++ - 你如何删除一个 vector ? C++

c++ - 如何在openMP中组合n个线程的私有(private)变量?

c++ - vs2005和vs2010模板函数的优先级不同

java - GIWS 在构建类时终止进程

c++ - 将多个视频文件合并为一个 mpeg-ts 文件 "on the fly"

c++ - 音频操作和删除音频的某些部分

c++ - 如果树的根改变了怎么办?

c++ - 是否可以在 VS2008 中的预处理器指令 block (如 #ifndef ... #endif)中启用智能感知

c++ - 如何将 boost::filesystem::directory_entry::path() 值分配给字符串?

c++ - 如何在更多线程上运行 boost asio 解析器服务?