Reputation: 23
I'm very new to programming, but am trying to learn both Python and C++ (One is work-related, other one is more of a spare-time thing). I use the following code in C++ to take measurements with a parking sensor:
> for (i=0; i<20; i++) {
> digitalWrite(TRIG1, LOW);
> delay(2);
> digitalWrite(TRIG1, HIGH);
> delay(10);
> digitalWrite(TRIG1, LOW);
> d = pulseIn(ECHO1, HIGH);
> d = d/58;
> delay(13);
> }
This should measure the distance and store it in d
. It will do this 20 times in a timespan of 500ms. I now want to store each of these 20 measurements and obtain the median value from it.
In Python, I can create a list, and then append numbers to it. Is there any such equivalent in C++? If not, what other method would be recommended to take a median value, without writing terribly long code?
Upvotes: 0
Views: 1942
Reputation: 1811
If you have to go with plain C(++) use an array of integer values:
int d[20];
for(int i = 0; i < 20; ++i)
d[i] = measureValue();
If the STL (Standard Template Library) is available, use a std::vector:
#include <vector>
std::vector<int> d;
for(int i = 0; i < 20; ++i)
d.push_back(measureValue());
If you are writing for an arduino, you may want to install Standard C++ for Arduino (see https://github.com/maniacbug/StandardCplusplus/blob/master/README.md)
Upvotes: 1