博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
reverse() 几种操作
阅读量:4286 次
发布时间:2019-05-27

本文共 2737 字,大约阅读时间需要 9 分钟。

#include 
#include
#include
#include
inline void STL_Reverse(std::string& str) // 反转string字符串 包装STL的reverse() 可以inline{ reverse(str.begin(), str.end()); // STL 反转函数 reverse() 的实现 /* template
* void reverse(BidirectionalIterator first, BidirectionalIterator last) * { * while ((first != last) && (first != --last)) * swap(*first++, *last); * } */} void bad_Reverse(std::string& str) // 效率低的反转字符串函数{ 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字符串反转函数{ // 效率比 C++ Primer Plus 的高一点 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字符串反转函数{ // 来源 C++ Primer Plus 第五章 forstr2.cpp -- reversing an array char 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) // 效率低的反转字符串函数 适合C风格字符串{ 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风格字符串反转函数{ // 效率没有 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风格字符串反转函数{ // 来源 C++ Primer Plus 第五章 forstr2.cpp -- reversing an array char 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 字符串反序函数测试,分别测试同样算法,string 和 C风格字符串的区别 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;}

转载地址:http://wdsgi.baihongyu.com/

你可能感兴趣的文章