Tips:此Code引用了STL库,已引用函数注释如下:
Origin Url:http://www.cplusplus.com/reference/algorithm/reverse/
template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last);
反向范围
反转范围中元素的顺序
[first,last)
。
函数调用iter_swap将元素交换到新位置。
此函数模板的行为等效于:template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last) { while ((first != last) && (first != --last)) { std::iter_swap (first, last); ++first; }; };
参数 first, last
双向迭代器到要反转的序列的初始和最终位置。使用的范围是
[first,last)
,它包含所有的元件第一和最后一个,包括由指向的元件第一但不被指向的元素最后。
BidirectionalIterator 应指向哪种类型 交换 是否正确定义。
例子
// reverse algorithm example #include <iostream> // std::cout #include <algorithm> // std::reverse #include <vector> // std::vector int main () { std::vector<int> myvector; // set some values: for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9 std::reverse(myvector.begin(),myvector.end()); // 9 8 7 6 5 4 3 2 1 // print out content: std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; }
输出:myvector contains: 9 8 7 6 5 4 3 2 1
程序代码:
#include <algorithm>
#include <iostream>
#include <string>
#include <cstdio>
#include <cctype>
using namespace std;
const char Form[] = {"0123456789ABCDEF"};
inline int data(const char ch) {
for (int i = 0; i < 16; ++i)
if (ch == Form[i])
return i;
return -1;
};
inline void a_to_decimal(const int a, string &str) {
const int len = str.length();
int answer = 0; int weight = 1;
for (int i = len - 1; i >= 0; --i) {
int temp = data(str[i]);
answer += temp * weight;
weight *= a;
};
string cache = "";
while (answer > 0) {
cache.push_back(answer % 10 + '0');
answer /= 10;
};
reverse(cache.begin(), cache.end());
str = cache;
};
inline void decimal_to_b(const int b, string &str) {
const int len = str.length();
int answer = 0; int weight = 1;
for (int i = len - 1; i >= 0; --i) {
int temp = data(str[i]);
answer += temp * weight;
weight *= 10;
};
string cache = "";
while (answer > 0) {
cache.push_back(Form[answer % b]);
answer /= b;
};
reverse(cache.begin(), cache.end());
str = cache;
};
inline void conversion(const int a, string &str, const int b) {
a_to_decimal(a, str);
decimal_to_b(b, str);
if (str.empty()) str.push_back('0');
};
int main(int argc, char *argv[]) {
int a, b; string str; cin >> a >> str >> b;
for (int i = 0; i < str.size(); ++i) str[i] = toupper(str[i]);
conversion(a, str, b);
cout << str << endl;
return 0;
};