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進行容器的逆置,要注意包含頭文件。兩種方法都很簡單和方便。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM