C++如何遍历数组vector

在C++中,vector是一个可变数组。那么怎么遍历它呢?我们以for循环为例(while循环,大家自己脑补)。

方法一:

基于范围的for循环,这是C++11新引入的。

cpp 复制代码
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (const auto element : v) {
	std::cout << element << std::endl;
}

方法二:

使用迭代器。

cpp 复制代码
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (auto element = v.begin(); element != v.end(); ++element) {
    std::cout << *element << std::endl;
}

v.begin()是第一个元素的指针,v.end()指向空(null)。++element是移动指针。

方法三:

这一种方式最传统,通过下标来遍历元素。

cpp 复制代码
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (size_t i = 0; i < v.size(); ++i) {
	std::cout << v[i] << std::endl;
}

在此也给出C语言中遍历数组的方法:

c 复制代码
const int v[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
const int size = sizeof(v) / sizeof(v[0]);
for (int i = 0; i < size; i++) {
   printf("v[%d] = %d\n", i, v[i]);
}
相关推荐
踏着七彩祥云的小丑1 天前
pytest——Mark标记
开发语言·python·pytest
Dream of maid1 天前
Python12(网络编程)
开发语言·网络·php
W23035765731 天前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
.Ashy.1 天前
2026.4.11 蓝桥杯软件类C/C++ G组山东省赛 小记
c语言·c++·蓝桥杯
Y4090011 天前
【多线程】线程安全(1)
java·开发语言·jvm
不爱吃炸鸡柳1 天前
Python入门第一课:零基础认识Python + 环境搭建 + 基础语法精讲
开发语言·python
minji...1 天前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
Dxy12393102161 天前
Python基于BERT的上下文纠错详解
开发语言·python·bert