首页  >  文章  >  后端开发  >  如何遍历C++ STL容器?

如何遍历C++ STL容器?

WBOY
WBOY原创
2024-06-05 18:29:01351浏览

要遍历 STL 容器,可以使用容器的 begin() 和 end() 函数获取迭代器范围:向量:使用 for 循环遍历迭代器范围。链表:使用 next() 成员函数遍历链表元素。映射:获取键值对迭代器,使用 for 循环遍历。

如何遍历C++ STL容器?

如何遍历 C++ STL 容器

遍历 C++ 标准模版库 (STL) 容器是程序员日常工作中必不可少的一项任务。STL 提供了一系列预定义数据结构,如向量、链表和映射,每个结构都有自己的遍历方法。

遍历 STL 矢量

要遍历一个矢量,我们可以使用 begin()end() 函数获得迭代器范围:

#include <vector>

int main() {
  std::vector<int> v = {1, 2, 3, 4, 5};

  // 使用基于范围的 for 循环
  for (int num : v) {
    std::cout << num << " ";
  }

  std::cout << std::endl;

  // 使用迭代器
  for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
    std::cout << *it << " ";
  }

  std::cout << std::endl;

  return 0;
}

输出:

1 2 3 4 5 
1 2 3 4 5 

遍历 STL 链表

要遍历一个链表,我们可以使用链表的 front()back() 函数以及该链表的 next() 成员函数:

#include <list>

int main() {
  std::list<int> l = {1, 2, 3, 4, 5};

  // 使用基于范围的 for 循环
  for (int num : l) {
    std::cout << num << " ";
  }

  std::cout << std::endl;

  // 使用迭代器
  std::list<int>::iterator it = l.begin();
  while (it != l.end()) {
    std::cout << *it << " ";
    it = it->next();
  }

  std::cout << std::endl;

  return 0;
}

输出:

1 2 3 4 5 
1 2 3 4 5 

遍历 STL 映射

要遍历一个映射,我们可以使用映射的 begin()end() 函数获取键值对的迭代器:

#include <map>

int main() {
  std::map<std::string, int> m = {{"Apple", 1}, {"Banana", 2}, {"Cherry", 3}};

  // 使用基于范围的 for 循环
  for (auto const& [key, value] : m) {
    std::cout << key << ": " << value << std::endl;
  }

  std::cout << std::endl;

  // 使用迭代器
  for (std::map<std::string, int>::iterator it = m.begin(); it != m.end(); ++it) {
    std::cout << it->first << ": " << it->second << std::endl;
  }

  return 0;
}

输出:

Apple: 1
Banana: 2
Cherry: 3

Apple: 1
Banana: 2
Cherry: 3

以上是如何遍历C++ STL容器?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn