• C++中vector容器的逆序访问


      今天在写个小的十进制转换程序时,遇到个问题就是关于vector容器的逆序访问问题,后来知道其中有多种方法可以解决,下面介绍我应用的两种简单方法,顺便熟悉一下vector容器的相关函数。下面是相关代码:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    int main()
    {
        int a = 0, d = 0, answer1 = 0, mod = 0, answer2 = 0;
        vector<int> m;
        cout << "Please input the number :" << endl;
        cin >> a;
        cout << "Please input the scale :" << endl;
        cin >> d;
        while (a)
        {
            mod = a%d;
            a = a / d;
            m.push_back(mod);
        }
        for (vector<int>::reverse_iterator it = m.rbegin(); it != m.rend(); it++)
        {
            answer2 = (*it) + answer2 * 10;
        }
    reverse(m.begin(), m.end());
    for (vector<int>::iterator it = m.begin(); it != m.end(); it++) { answer1 = (*it)+answer1*10
    ; } cout << answer1 << endl; cout << answer2 << endl; }

      程序中用蓝色和黄色标记的分别是两种不同的方法,第一种利用的是逆置迭代器,要注意逆置迭代器的初始化。第二种是利用头文件<algorithm>中的函数reverse进行容器的逆置,要注意包含头文件。两种方法都很简单和方便。

  • 相关阅读:
    原型与继承
    sqlserver优化管理
    vue 错误拦截
    axios 重新发起上次请求
    vue 滚动加载数据
    el-scrollbar组件
    ES服务器优化
    Aspose 生成pdf行距的不正确的问题,行距变高
    DocumentFormat.OpenXml.dll通過word做好的模板生成word
    stm32f103 rt-thread fal easyflash移植过程
  • 原文地址:https://www.cnblogs.com/helloforworld/p/5452554.html
Copyright © 2020-2023  润新知