好吧,我知道这听起来可能令人困惑 - 我是编程概念的新手。 我有一个 CNC 项目,它将从文本文件中获取值,分配它们,并通过串行连接将它们传输到 Arduino,Arduino 将接收和驱动电机,等等。
for( std::string line; getline( input, line ); )
{
int x, y;
input >> x >> y;
}
但是,我希望能够让程序处理任意长度的文本文件 - 任意数量的坐标。在界面中,我正在设计一个允许用户指定命令数量的输入面板。但是,我该如何引入接受那么多命令并引入那么多变量的代码呢?我知道我可以通过为每个 X、Y、Z
和其他命令类型创建 1000
变量来暴力破解它,并且最多有 1000
可能的线路处理,但如果有代码可以实现这一点并为我进行调整,效率会更高。
例如,我让文本输入框输出一个指定的值 NumberOfCommands
。我如何告诉程序创建多个 X 轴、Y 轴和 Z 轴
(以及其他串行)命令,其中该数字等于 NumberOfCommands
?
最佳答案
您可以使用 std::vector
类来存储任意数量的元素。
所以在你的情况下是这样的:
struct Coordinate {
int x,y,z;
};
std::vector<Coordinate> coords;
for( std::string line; getline( input, line ); )
{
Coordinate coord;
input >> coord.x >> coord.y >> coord.z;
coords.push_back(coord);
}
或者使用emplace_back
:
struct Coordinate {
Coordinate(int x, int y, int z):x(x),y(y),z(z){ }
int x,y,z;
};
std::vector<Coordinate> coords;
int x,y,z;
for( std::string line; getline( input, line ); )
{
input >> x >> y >> z;
coords.emplace_back(x,y,z);
}
emplace_back
不像 push_back
那样制作拷贝,它创建元素并将其放入 vector 中。
关于c++ - 如何设置不定数量的变量,由另一个变量指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16744786/