遍历std::vector<double>容器,打印
时间: 2024-09-09 22:09:41 浏览: 64
遍历`std::vector<double>`容器并打印其元素可以通过多种方法实现,这里介绍两种常见的遍历方式:使用范围基的for循环和使用迭代器。
1. 使用范围基的for循环:
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<double> vec = {1.5, 2.5, 3.5, 4.5}; // 初始化vector
for (const auto& value : vec) { // 遍历vector中的每个元素
std::cout << value << std::endl; // 打印每个元素
}
return 0;
}
```
2. 使用迭代器:
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<double> vec = {1.5, 2.5, 3.5, 4.5}; // 初始化vector
for (auto it = vec.begin(); it != vec.end(); ++it) { // 使用迭代器遍历vector
std::cout << *it << std::endl; // 解引用迭代器并打印元素
}
return 0;
}
```
在这两种方法中,范围基的for循环代码更加简洁易读,而使用迭代器则提供了更多的控制灵活性,特别是在需要修改遍历的元素或者在遍历过程中进行复杂的操作时。
阅读全文
相关推荐



















