栈的一个典型应用就是进制转换
#include "../head.h"
#include <stack>
void convert(stack<char, vector<char>> &s, int n, int base) {
const static char digit[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b','c','d','e','f'};
while (n > 0) {
s.push(digit[n % base]);
n /= base;
}
}
int main(int argc, char** argv) {
stack<char, vector<char>> s;
int n, base;
cout << "what's your number: "; cin >> n;
cout << "what's your decimal: "; cin >> base;
convert(s, n, base);
while (!s.empty()) {
cout << s.top();
s.pop();
}
cout << endl;
return 0;
}
这里使用了c++的适配器栈,它默认基于deque实现,这里将其转换为用vector实现,这里可以指定任意进制(别超过16)来对输入的十进制数进行进制转换,原理也十分简单,就是对指定数字不断的取模、压栈,然后从栈顶一个个将元素弹出即可