一、函数reverse()

第一种是利用头文件<algorithm>中的函数reverse进行容器的逆置,要注意包含头文件;

    //第一种
    reverse(m.begin(), m.end());
    for (vector<int>::iterator it = m.begin(); it != m.end(); it++){
        answer1 = (*it)+answer1*10;
    }

二、for遍历

第二种利用的是逆置迭代器,要注意逆置迭代器的初始化;

    //第二种
    for (vector<int>::reverse_iterator it = m.rbegin(); it != m.rend(); it++){
        answer2 = (*it) + answer2 * 10;
    }
    //第二种【用auto自动推导】
    for (auto it = m.rbegin(); it != m.rend(); it++){
        answer2 = (*it) + answer2 * 10;
    }

三、全部代码

#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);
    }
 
    //第一种
    reverse(m.begin(), m.end());
    for (vector<int>::iterator it = m.begin(); it != m.end(); it++){
        answer1 = (*it)+answer1*10;
    }
 
    //第二种
    for (vector<int>::reverse_iterator it = m.rbegin(); it != m.rend(); it++){
        answer2 = (*it) + answer2 * 10;
    }
 
 
    cout << answer1 << endl;
    cout << answer2 << endl;
}




C++中vector容器的逆序遍历访问 – 星辰的博客

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐