Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ranged based for loop

Tags:

c++

Trying to do something with a ranged based for loop. It can be done with a regular for loop like this:

vector<double> sensorReadings(3);
sensorReadings = {0,0,0};

for (int i = 0; i < sensorReadings.size();i++)
{
    sensorReadings[i] += i + 100 ;

}

I want to set a vector's first element equal to n (100 in this case) and set every other element equal to n+1. In this case after the above loop runs the vector is 100,101,102, as desired. My problem is doing this with a range base loop always sets all the elements to be the same value. How do I make the above loop into a range based for loop? My attempt is below:

vector<double> sensorReadings(3);
sensorReadings = {0,0,0};


for(double &sensorVal: sensorReadings)
{
    double y = 100;
    sensorVal = y;
    y++;
}


for (double i: sensorReadings)
   cout << " " << i ;

This loop just sets all values of the vector equal to 100

any help would be great, thanks!

like image 415
John Avatar asked May 14 '26 06:05

John


2 Answers

I find that not using a raw loop at all can sometimes be even better. There's a name for the operation you are doing, so the standard library has an algorithm that does just that. It's std::iota

vector<double> sensorReadings(3);
std::iota(begin(sensorReadings), end(sensorReadings), 100);

Now there's no need to mentally parse the loop to know what it's doing, nor is there a need to introduce a superfluous variable.

like image 133
StoryTeller - Unslander Monica Avatar answered May 15 '26 20:05

StoryTeller - Unslander Monica


double y = 100;
for(double &sensorVal: sensorReadings)
{
    sensorVal = y;
    y++;
}
like image 24
Jay Wai Tan Avatar answered May 15 '26 20:05

Jay Wai Tan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!