【问题标题】:How to set a indefinite number of variables, specified by another variable如何设置由另一个变量指定的不定数量的变量
【发布时间】:2013-05-24 23:11:13
【问题描述】:

好的,我知道这听起来可能令人困惑 - 我是编程理念的新手。 我有一个 CNC 项目,它将从文本文件中获取值,分配它们,然后通过串行连接将它们传输到 Arduino,Arduino 将接收和驱动电机,依此类推。

for( std::string line; getline( input, line ); ) 
{
int x, y;
input >> x >> y;
}

但是,我希望能够让程序处理任意长度的文本文件——任意数量的坐标。在界面中,我正在设计一个输入面板,允许用户指定命令的数量。但是,我如何引入可以采用这么多命令并引入这么多变量的代码呢?我知道我可以通过创建每个X, Y, Z 和其他命令类型的1000 变量来强制执行此操作,并且最多有1000 可能的行处理,但是拥有实现这一点的代码和适合我。

例如,我让文本输入框输出一个指定为NumberOfCommands 的值。我将如何告诉程序创建多个等于NumberOfCommandsX-axis, Y-axis, and Z-axis(以及其他串行)命令?

【问题讨论】:

标签: c++ variables cnc indefinite


【解决方案1】:

您可以使用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 那样制作副本,它会创建元素并将其放入向量中。

【讨论】:

  • 现在,形式为 x(x),y(y),z(z);括号中的 x/y/z 是数字吗?也就是说,我可以在代码 serial.write(x(4)) 中注明第四组坐标吗?
  • 括号里面的x是传递给构造函数的参数x,是emplace_back的第一个参数。括号外的x 是成员变量x。当您将其发送到 serial.write 时,您将使用 serial.write(coords[0].x) 发送第 0 个元素的 x 成员。
【解决方案2】:

您可以使用动态调整大小的数组。

例如from here:

int *myArray;           //Declare pointer to type of array
myArray = new int[x];   //use 'new' to create array of size x
myArray[3] = 10;        //Use as normal (static) array
...
delete [] myArrray;     //remember to free memory when finished.

问题是x 来自哪里?您可以假设 1000 并在填充数组时保持计数。然后,如果您获得的信息超过该大小,则可以调整数组的大小。

或者你可以从一个实体开始,比如 STL vector&lt;int&gt;

【讨论】:

  • 这是 C++ 而不是 C。请不要建议使用数组,尤其是与裸指针结合使用:这是搞砸事情的最佳方式。
猜你喜欢
  • 1970-01-01
  • 2022-01-10
  • 2022-10-22
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
相关资源
最近更新 更多