[英]C++ ranged based for loop
Trying to do something with a ranged based for loop. 尝试使用基于范围的for循环执行某些操作。 It can be done with a regular for loop like this:
可以使用这样的常规for循环来完成:
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. 我想设置一个向量的第一个元素,它等于n(在这种情况下为100),并将每个其他元素设置为等于n + 1。 In this case after the above loop runs the vector is 100,101,102, as desired.
在这种情况下,在上述循环运行之后,矢量是100,101,102,如期望的那样。 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 此循环仅将向量的所有值设置为100
any help would be great, thanks! 任何帮助都会很棒,谢谢!
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
这是
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. 现在没有必要在精神上解析循环以了解它正在做什么,也不需要引入多余的变量。
double y = 100;
for(double &sensorVal: sensorReadings)
{
sensorVal = y;
y++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.