C++-vector:vector容器逆序遍历【for (auto it = v.rbegin(); it != v.rend(); it++){}】

 一、函数reverse()

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

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

二、for遍历

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

    //第二种
    for (vector::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 
#include 
#include 
using namespace std;
 
int main(){
    int a = 0, d = 0, answer1 = 0, mod = 0, answer2 = 0;
    vector 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::iterator it = m.begin(); it != m.end(); it++){
        answer1 = (*it)+answer1*10;
    }
 
    //第二种
    for (vector::reverse_iterator it = m.rbegin(); it != m.rend(); it++){
        answer2 = (*it) + answer2 * 10;
    }
 
 
    cout << answer1 << endl;
    cout << answer2 << endl;
}

 




 

你可能感兴趣的:(#,c++,算法,开发语言)