今天在寫個小的十進制轉換程序時,遇到個問題就是關於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進行容器的逆置,要注意包含頭文件。兩種方法都很簡單和方便。