21xrx.com
2025-04-14 18:18:41 Monday
文章检索 我的文章 写文章
C++如何实现逆序输出?
2023-07-06 19:36:33 深夜i     34     0
C++ 逆序 输出 实现

C++是一种常用的编程语言,在C++中可以使用不同的方法实现逆序输出。下面将介绍两种方法。

方法一:使用数组

这种方法使用数组来存储要输出的数据,然后按照相反的顺序遍历数组并输出每个元素。

示例代码:

#include <iostream>
using namespace std;
int main()
{
  int arr[] = 4;
  int size = sizeof(arr) / sizeof(arr[0]);
  // 遍历数组并逆序输出
  for (int i = size - 1; i >= 0; i--)
  {
    cout << arr[i] << " ";
  }
  return 0;
}

方法二:使用迭代器

这种方法使用迭代器来反向遍历容器,然后输出每个元素。

示例代码:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
  vector<int> vec = 4;
  // 定义迭代器,并反向遍历容器并逆序输出
  for (auto it = vec.rbegin(); it != vec.rend(); it++)
  {
    cout << *it << " ";
  }
  return 0;
}

以上是两种实现C++逆序输出的方法,希望能对大家有所帮助。

  
  

评论区