21xrx.com
2024-05-20 17:16:54 Monday
登录
文章检索 我的文章 写文章
C++ Vector 的遍历方法
2023-07-12 03:26:41 深夜i     --     --
C++ Vector 遍历 方法 迭代器

C++ Vector是一个十分常用的容器,在进行C++编程时几乎随意都能见到它的身影。在平时使用Vector时,我们经常需要对Vector进行遍历,来对Vector中的元素进行操作。本文将会介绍C++ Vector的遍历方法,供读者参考。

1. for循环遍历

for循环遍历是最简单的遍历方法,将Vector中的元素一个一个地访问并进行操作。以下是使用for循环遍历Vector的范例代码:


#include <iostream>

#include <vector>

using namespace std;

int main() {

  vector<int> vec1;

  

  for(int i = 0; i < vec.size(); i++) {

    cout << vec[i] << " ";

  }

  cout << endl;

  return 0;

}

运行结果为:


1 2 3 4 5

2. 迭代器遍历

迭代器遍历是较为常用的遍历方法,通过迭代器来访问Vector中的元素。以下是使用迭代器遍历Vector的代码:


#include <iostream>

#include <vector>

using namespace std;

int main() {

  vector<int> vec 3;

  

  for(auto it = vec.begin(); it != vec.end(); it++) {

    cout << *it << " ";

  }

  cout << endl;

  return 0;

}

运行结果为:


1 2 3 4 5

可以看出,迭代器遍历的效果和for循环遍历是完全一样的。

3. C++11 foreach循环遍历

C++11引入了foreach循环遍历的语法,可以大大简化Vector的遍历操作。以下是使用C++11 foreach循环遍历Vector的代码:


#include <iostream>

#include <vector>

using namespace std;

int main() {

  vector<int> vec 5;

  

  for(auto elem : vec)

    cout << elem << " ";

  

  cout << endl;

  return 0;

}

运行结果为:


1 2 3 4 5

可以看出,使用C++11 foreach循环遍历可以在代码量更少的情况下完成与for循环遍历一样的操作。

总结

本文介绍了C++ Vector的三种常用遍历方法,要根据实际情况选择合适的方法,使代码更为简洁与高效。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复