问题描述:在Arduino中,如果结构体向量未正确填充,则可能会导致值错误。此问题通常出现在C++中使用Arduino的情况下。下面提供了一个简单的解决方案。
示例代码:
// Create a structure with two elements
struct car {
int id;
float speed;
};
// Create a vector to hold the car structs
std::vector cars;
void setup() {
// Add some car structs to the vector
car new_car;
new_car.id = 1;
new_car.speed = 20.0;
cars.push_back(new_car);
new_car.id = 2;
new_car.speed = 30.0;
cars.push_back(new_car);
new_car.id = 3;
new_car.speed = 40.0;
cars.push_back(new_car);
// Print the car ids and speeds to the serial monitor
for (int i = 0; i < cars.size(); i++) {
Serial.print("Car ");
Serial.print(cars[i].id);
Serial.print(" speed ");
Serial.println(cars[i].speed);
}
}
void loop() {
// Do nothing
}
在上述示例中,首先创建一个名为car
的结构体,其中包含id
和speed
两个元素。接下来,创建一个名为cars
的向量,用于保存car
结构体。最后,使用push_back
函数将三个不同的car
结构体添加到向量中。
在循环中,可以使用size()
函数遍历cars
向量,并使用Serial.print
函数打印id
和speed
值。
请注意,在Arduino IDE中,需要启用C++11标志才能使用向量。为此,请选择菜单中的“文件”-“首选项”-“额外文件夹URL”,并将以下网址添加到“附加开