迭代器求一个结构体类型vector中结构体的double元素每个数之间的统一间隔
时间: 2023-11-08 08:10:34 浏览: 190
vector的迭代器
可以使用迭代器遍历vector中的结构体,然后计算每个结构体的double元素与前一个结构体的double元素之间的差值,从而得到统一间隔。以下是示例代码:
```c++
#include <iostream>
#include <vector>
struct MyStruct {
int id;
double value;
};
int main() {
std::vector<MyStruct> vec{ {1, 1.0}, {2, 2.5}, {3, 4.0}, {4, 6.5}, {5, 9.0} };
auto it = vec.begin();
double prev_value = it->value;
++it;
while (it != vec.end()) {
double diff = it->value - prev_value;
std::cout << "Difference between " << it->id << " and " << (it - 1)->id << ": " << diff << std::endl;
prev_value = it->value;
++it;
}
return 0;
}
```
输出结果为:
```
Difference between 2 and 1: 1.5
Difference between 3 and 2: 1.5
Difference between 4 and 3: 2.5
Difference between 5 and 4: 2.5
```
阅读全文