C++ 迭代对象列表
在JavaScript中,我可能迭代一组包含数据的对象,如下所示:C++ 迭代对象列表,c++,arduino,C++,Arduino,在JavaScript中,我可能迭代一组包含数据的对象,如下所示: const components = [ { id: 1, pin: "A0", name: "light" }, { id: 2, pin: "A1", name: "sound" }, { id: 1, pin: "A0", name: "heat" }, ] for (const component of compon
const components = [
{
id: 1,
pin: "A0",
name: "light"
},
{
id: 2,
pin: "A1",
name: "sound"
},
{
id: 1,
pin: "A0",
name: "heat"
},
]
for (const component of components) {
const value = analogRead(component.pin);
console.log(`${component.name}:value`)
}
我经常需要在Arduino上使用这样的代码,但我不知道该怎么做
注:我不想把这个翻译成C++。我想知道标准模式是什么,当使用ARDUIIO。< /P> < P>如果你使用的是现代C++(11或更新,我理解ARDUINO支持),并且你的数据被存储在一个数组中,你可以简单地做如下:
int values[5] = { 16, 2, 77, 40, 12071 }
for(auto const& value: values) {
// Do stuff
}
您可以使用
C结构
。为此,您需要首先声明一个描述对象类型的结构
struct component
{
int id;
char pin[10];
char name[50];
};
component components[] = {
{
1,
"A0",
"light"},
{
2,
"A1",
"sound"},
{
1,
"A0",
"heat"}
};
int main ()
{
int len = sizeof(components)/sizeof(components[0]);
for (int i=0 ; i<len ; i++)
{
printf("{ id: %d , pin: \"%s\" , name: \"%s\" }\n",components[i].id, components[i].pin, components[i].name);
}
return 0;
}
C++中的翻译与C.的翻译有100%种不同,你所看到的是可以翻译的C++,或多或少。类似的工作可以在C中完成,但它需要更多的工作。您真正使用的是哪种语言?一个很好的参考是:。无论如何,C++中没有一种标准的方法。谷歌会在这方面帮上大忙不确定这是否正确,但如果你把它贴在Arduino论坛上会更好,所以不能从头教你一门语言。你的问题被任何C++书籍回答。请注意,实现的标准版本和风格都有不同(例如,对于像ARDUNO这样的小系统),所以不是每个有效的C++解决方案都适用于您的环境。对于那些想要回答的人:请记住ARDUINO平台没有C++ C++标准库。ARDUINO LIB没有C++ STD库。arduinoAh上没有像
std::vector
这样的容器,你说得对。更新的答案改为引用简单数组。@Juraj没问题:D
{ id: 1 , pin: "A0" , name: "light" }
{ id: 2 , pin: "A1" , name: "sound" }
{ id: 1 , pin: "A0" , name: "heat" }