Iterate over a list of objects - c++

In JavaScript I might iterate over a set of objects containing data, like this:
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`)
}
I often have a need to use code like this on the Arduino, but I'm not sure how I'd go about it.
NOTE: I'm not looking for an exact translation of this into C++; I want to know what the standard pattern is for achieving this is when using Arduino.

You can use C structure. To do so you need to declare a structure first describing your object type.
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;
}
Output:
{ id: 1 , pin: "A0" , name: "light" }
{ id: 2 , pin: "A1" , name: "sound" }
{ id: 1 , pin: "A0" , name: "heat" }

If you're using modern C++ (11 or newer, which I understand arduino support), and your data is stored in an array you can simply do the following:
int values[5] = { 16, 2, 77, 40, 12071 }
for(auto const& value: values) {
// Do stuff
}

Related

Swift Storing Appending multiple Dictionary into array

I want to store multiple dictionary into an array so that the final results looks like so
(
{
id: 12,
task : completed
},
{
id: 15,
task : error
},
{
id: 17,
task : pending
},
)
I tried with code below but it does not give me what I want Please can someone help me out. Thanks
var FinalTaskData = [[String:AnyObject]]()
for i in 0..<taskObj.count{
let dict = ["id":taskObj[i].id!,"task":taskObj[i].task!] as [String : AnyObject]
FinalTaskData.append(dict)
}
And this gives me the output of
(
{
id = 190;
},
{
task = "Task To Be Edited";
},
{
id = 191;
},
{
task = "Also To Be Edited";
}
)
Which is not what I want. Thanks

MongoDB writing a query for search engine

I am trying to write a search script in MongoDB but can't figure out how to do it....The thing I wan't to do is as follows....
Lets I have a string array XD = {"the","new","world"}
Now i want to search string array XD in MongoDB document (using regex) and get the result document. For example..
{ _id: 1, _content: "there was a boy" }
{ _id: 2, _content: "there was a boy in a new world" }
{ _id: 3, _content: "a boy" }
{ _id: 4, _content: "there was a boy in world" }
now I want to get result in accordance to _content contains the string in string array XD
{ _id: 2, _content: "there was a boy in a new world", _times: 3 }
{ _id: 4, _content: "there was a boy in world", times: 2 }
{ _id: 1, _content: "there was a boy", times: 1 }
as first document (_id : 2 ) contains all three { "the" in there, "new" as new, "world" as world } so it got 3
second document (_id: 4) only two { "world" as world } so it got 2
Here is what you can do.
Create a Regex to be matched with _content
XD = ["the","new","world"];
regex = new RegExp(XD.join("|"), "g");
Store a JS function on the server, which matches the _content with XD and returns the counts matched
db.system.js.save(
{
_id: "findMatchCount",
value : function(str, regexStr) {
XD = ["the","new","world"];
var matches = str.match(regexStr);
return (matches !== null) ? matches.length : 0;
}
}
)
Use the function with mapReduce
db.test.mapReduce(
function(regex) {
emit(this._id, findMatchCount(this._content, regex));
},
function(key,values) {
return values;
},
{ "out": { "inline": 0 } }
);
This will produce the output as below:
{
"results" : [
{
"_id" : 1,
"value" : 1
},
{
"_id" : 2,
"value" : 1
},
{
"_id" : 3,
"value" : 1
},
{
"_id" : 4,
"value" : 1
}
],
"timeMillis" : 1,
"counts" : {
"input" : 4,
"emit" : 4,
"reduce" : 0,
"output" : 4
},
"ok" : 1
}
I am not sure how efficient this solution is but it works.
Hope this helps.

d3.js function to count data belonging to a category and bigger than 0

I am trying to create a function that counts the people of each category that have a value bigger than 0. If this is my data...
DATA.CSV
name; category; value
name1; A; 10
name2; A; 0
name3; A; 5
name4; B; 7
name5; B; 3
name6; C; 0
...I should get the following results
count(dataset, "A")=2
count(dataset, "B")=2
count(dataset, "C")=0
EDIT! I am actually loading data from a .json file
[
{
"voce":"amministrazione",
"categoria":"funzioni",
"val2015":404571081
},
{
"voce":"sociale",
"categoria":"funzioni",
"val2015":235251679
},
{
"voce":"territorio e ambiente",
"categoria":"funzioni",
"val2015":286164667
},
{
"voce":"viabilità e trasporti ",
"categoria":"funzioni",
"val2015":144185664
},
{
"voce":"istruzione",
"categoria":"funzioni",
"val2015":168774925
},
{
"voce":"cultura ",
"categoria":"funzioni",
"val2015":55868045
},
{
"voce":"sport",
"categoria":"funzioni",
"val2015":27219432
},
{
"voce":"turismo",
"categoria":"funzioni",
"val2015":9544845
},
{
"voce":"sviluppo economico",
"categoria":"funzioni",
"val2015":14790363
},
{
"voce":"servizi produttivi",
"categoria":"funzioni",
"val2015":4334
},
{
"voce":"polizia locale",
"categoria":"funzioni",
"val2015":99007202
},
{
"voce":"giustizia ",
"categoria":"funzioni",
"val2015":12147068
},
{
"voce":"anticipazioni di cassa",
"categoria":"rimborso prestiti",
"val2015":304323808
},
{
"voce":"finanziamenti a breve termine",
"categoria":"rimborso prestiti",
"val2015":0
},
{
"voce":"prestiti obbligazionari",
"categoria":"rimborso prestiti",
"val2015":38842996
},
{
"voce":"quota capitale di debiti pluriennali",
"categoria":"rimborso prestiti",
"val2015":0
},
{
"voce":"quota capitale di mutui e prestiti",
"categoria":"rimborso prestiti",
"val2015":128508755
},
{
"voce":"spese per conto terzi",
"categoria":"",
"val2015":232661261
},
{
"voce":"disavanzo di amministrazione",
"categoria":"",
"val2015":0
}
]
I tried a for loop with an if statement inside but it is not working.
function count (dataset, chosenCategory) {
var count = 0;
for (d in dataset) {
if (d.categoria==chosenCategory && d.val2015>0) {
count += 1;
} else {
count += 0;
}
}
}
What am I doing wrong?
have you tried changing "d.value" to "+d.value"?
If they're from a csv file, values are generally loaded as strings, so everything you want to treat as a number needs converted to a number, and the '+' does that.
try it in your console
"1">0
false
+"1">0
true
PS. You don't need the else condition

Using json-spirit to read json string in C++

How to use json-spirit to read json string in C++? I read the demo code.
I find that:
const Address addrs[5] = { { 42, "East Street", "Newtown", "Essex", "England" },
{ 1, "West Street", "Hull", "Yorkshire", "England" },
{ 12, "South Road", "Aberystwyth", "Dyfed", "Wales" },
{ 45, "North Road", "Paignton", "Devon", "England" },
{ 78, "Upper Street", "Ware", "Hertfordshire", "England" } };
Can I convert a String into a json object?
char* jsonStr = "{'name', 'Tom'}";
json_spirit provides bool read_string( const String_type& s, Value_type& value ) and bool read( const std::string& s, Value& value ) to read json data from strings.
Here is an example:
string name;
string jsonStr("{\"name\":\"Tom\"}");
json_spirit::Value val;
auto success = json_spirit::read_string(jsonStr, val);
if (success) {
auto jsonObject = val.get_obj();
for (auto entry : jsonObject) {
if (entry.name_ == "name" && entry.value_.type() == json_spirit::Value_type::str_type) {
name = entry.value_.get_str();
break;
}
}
}
You could also use ifstream instead of string to read from json from file.
Please note, according to RFC4627 a string begins and ends with quotation marks.

Problems accessing pre-defined array of floats in C++

I'm trying to make use of precalculated values by outputting them to a header file and then compiling them for use.
The precalculated values are cube co ordinates mapped onto a sphere and the data structure takes the form of:
typedef float heightMapCubeFace[5][5][3];
I am defining each face seperately like so:
heightMapCubeFace face1 = {{{ -2.88675, -2.88675, -2.88675 }, { -3.38502, -3.38502, -1.44338 }, { -3.53553, -3.53553, 0 }, { -3.38502, -3.38502, 1.44338 }, { -2.88675, -2.88675, 2.88675}},
{{ -1.44338, -3.38502, -3.38502 }, { -1.69251, -4.38986, -1.69251 }, { -1.76777, -4.67707, 0 }, { -1.69251, -4.38986, 1.69251 }, { -1.44338, -3.38502, 3.38502}},
{{ 0, -3.53553, -3.53553 }, { 0, -4.67707, -1.76777 }, { 0, -5, 0 }, { 0, -4.67707, 1.76777 }, { 0, -3.53553, 3.53553}},
{{ 1.44338, -3.38502, -3.38502 }, { 1.69251, -4.38986, -1.69251 }, { 1.76777, -4.67707, 0 }, { 1.69251, -4.38986, 1.69251 }, { 1.44338, -3.38502, 3.38502}},
{{ 2.88675, -2.88675, -2.88675 }, { 3.38502, -3.38502, -1.44338 }, { 3.53553, -3.53553, 0 }, { 3.38502, -3.38502, 1.44338 }, { 2.88675, -2.88675, 2.88675}}
};
and finally:
heightMapCubeFace * heightMapSaved[6] = {&face1, &face2, &face3, &face4, &face5, &face6};
Eventually the data structue will be bigger I hav ejust set it to 5x5 to make things easier at first.
The problem I am having is when I want to get the values back, something weird is happening and as a result access violations are occuring.
As shown in the following image
As you can see the assigned value does not match that of the data structure. Instead the value for index [0][0][0][1] is given the value of index [0][0][1][0].
here
I picked up on this because an unhaddled exception is thrown at a later stage (access violation), I think it is because of this index problem but can't be certain.
I don't understand what is going on, am I dereferencing the pointer wrong?
Any help would be much appriciated, thanks.
Here is the code for that section:
for(int i = 0; i < 6; i++)
{
for(int j = 0; j < heightMapRes; j++)
{
for(int k = 0; k < heightMapRes; k++)
{
float xCoord = *(heightMapSaved[i][j][k][0]);
float yCoord = *(heightMapSaved[i][j][k][1]);
float zCoord = *(heightMapSaved[i][j][k][2]);
float newValue = myModule.GetValue( xCoord, yCoord, zCoord);
heightMap.SetValue( j, k, newValue);
}
}
}
layout is (heightMapSaved[6])[5][5][3] not (heightMapSaved[5][5][3][6])