reverse() 几种操作
生活随笔
收集整理的這篇文章主要介紹了
reverse() 几种操作
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>inline void STL_Reverse(std::string& str) // 反轉(zhuǎn)string字符串 包裝STL的reverse() 可以inline
{reverse(str.begin(), str.end());// STL 反轉(zhuǎn)函數(shù) reverse() 的實(shí)現(xiàn)/* template <class BidirectionalIterator>* void reverse(BidirectionalIterator first, BidirectionalIterator last)* {* while ((first != last) && (first != --last))* swap(*first++, *last);* }*/
}void bad_Reverse(std::string& str) // 效率低的反轉(zhuǎn)字符串函數(shù)
{std::string tmp(str);std::string::size_type ix = str.length() - 1;for (std::string::size_type i = 0; i < str.length(); i++) {str[i] = tmp[ix];ix--;}
}void good_Reverse(std::string &word) // 仿制STL的算法的,適合string字符串反轉(zhuǎn)函數(shù)
{ // 效率比 C++ Primer Plus 的高一點(diǎn)size_t first, last;first = 0;last = word.size();while ((first != last) && (first != --last))std::swap(word[first++], word[last]);
}void Reverse(std::string &word) // 適合string字符串反轉(zhuǎn)函數(shù)
{ // 來源 C++ Primer Plus 第五章 forstr2.cpp -- reversing an arraychar temp;size_t i, j;for (j = 0, i = word.size() - 1; j < i; --i, ++j) {temp = word[i];word[i] = word[j];word[j] = temp;}
}void bad_Reverse(char *str) // 效率低的反轉(zhuǎn)字符串函數(shù) 適合C風(fēng)格字符串
{char * tmp = new char[strlen(str)];strcpy(tmp, str);size_t ix = strlen(str) - 1;for (size_t i = 0; i < strlen(str); i++) {str[i] = tmp[ix];ix--;}delete[] tmp;
}void good_Reverse(char *word) // 仿制STL的算法的,適合C風(fēng)格字符串反轉(zhuǎn)函數(shù)
{ // 效率沒有 C++ Primer Plus 的高size_t first, last;first = 0;last = strlen(word);while ((first != last) && (first != --last))std::swap(word[first++], word[last]);
}void Reverse(char *word) // 適合C風(fēng)格字符串反轉(zhuǎn)函數(shù)
{ // 來源 C++ Primer Plus 第五章 forstr2.cpp -- reversing an arraychar temp;size_t i, j;for (j = 0, i = strlen(word) - 1; j < i; --i, ++j) {temp = word[i];word[i] = word[j];word[j] = temp;}
}int main()
{using namespace std;// 1KW 字符串反序函數(shù)測(cè)試,分別測(cè)試同樣算法,string 和 C風(fēng)格字符串的區(qū)別string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";for (int i = 0 ; i != 10000001 ; i++)// STL_Reverse(str); //0.313秒// good_Reverse(str); //0.875秒// Reverse(str); //1.063秒bad_Reverse(str); //7.016秒cout << str << endl;char cs[] = "0123456789abcdefghijklmnopqrstuvwxyz";for (int i = 0 ; i != 10000001 ; i++)// Reverse(cs); //0.578秒// good_Reverse(cs); //0.859秒bad_Reverse(cs); //13.766秒cout << cs << endl;return 0;
}
總結(jié)
以上是生活随笔為你收集整理的reverse() 几种操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 专访《突破》作者刘朋: 程序员快速提升领
- 下一篇: GitHub 有望在中国开设子公司?