(一)用基本的數組實現
#include "stdafx.h" #include <stdio.h> #include <string.h> int main() { char ch1[10] = "abcde", ch2[10] = {0}; int n=0, i=0, j=0; n = strlen(ch1); for(i = n-1; i>=0; i--) { ch2[j] = ch1[i]; j++; } printf("%s\n%s\n", ch1, ch2); return 0; }
(二)加入向量vector, vector是具有方向的矢量容器,使用時,需include <vector>
#include "stdafx.h" #include <stdio.h> #include <string.h>
using namespace std;
#include <vector>
int main() { char ch1[10] = "abcde", ch2[10] = {0}; int n=0, i=0, j=0; n = strlen(ch1); vector <char> cVec(ch1, ch1+n); for(i = cVec.size()-1; i>=0; i--) { ch2[j] = ch1[i]; j++; } printf("%s\n%s\n", ch1, ch2); return 0; }
(三)加入迭代器(iterator), iterator是一中檢查容器內元素並遍歷元素的數據類型,每個容器都可以定義自己的迭代器。
使用迭代器,需include <iterator>
#include "stdafx.h" #include <stdio.h> #include <string.h> using namespace std; #include <vector> #include <iterator> int main() { char ch1[10] = "abcde", ch2[10] = {0}; int n=0, i=0, j=0; n = strlen(ch1); vector <char> cVec(ch1, ch1+n);
vector <char>::reverse_iterator cRIter;
for(cRIter=cVec.rbegin(); cRIter!=cVec.rend(); cRIter++) { ch2[j] = *cRIter;//同時也可更改*cRIter為cRIter[0]; j++; } printf("%s\n%s\n", ch1, ch2); return 0; }
(四)使用雙向鏈表list,list可以被視為一個雙向鏈表,每個元素都具有前后元素的鏈接
1. (同上為反向迭代器)
#include "stdafx.h" #include <stdio.h> #include <string.h> using namespace std; #include <list> #include <iterator> int main() { char ch1[10] = "abcde", ch2[10] = {0}; int n=0, i=0, j=0; n = strlen(ch1); list<char> cList(ch1, ch1+n); list<char>::reverse_iterator cRIter; for(cRIter=cList.rbegin(); cRIter!=cList.rend(); cRIter++) { ch2[j] = *cRIter; j++; } printf("%s\n%s\n", ch1, ch2); return 0; }
(四)使用雙向鏈表list,正向迭代器
#include "stdafx.h" #include <stdio.h> #include <string.h> using namespace std; #include <list> #include <iterator> int main() { char ch1[10] = "abcde", ch2[10] = {0}; int n=0, i=0, j=0; n = strlen(ch1); list<char> cList(ch1, ch1+n); list<char>::iterator cIter = cList.end(); cIter--; for(cIter; cIter!=cList.begin();cIter--) { ch2[j] = *cIter; j++; } if(cIter==cList.begin()) { ch2[j] = *cIter; } printf("%s\n%s\n", ch1, ch2); return 0; }
以上所有輸出結果為:
(五)使用雙向鏈表list,iterator正向迭代器復制的例子;
#include "stdafx.h" #include <stdio.h> #include <string.h> using namespace std; #include <list> #include <iterator> int main() { char ch1[10] = "abcde", ch2[10] = {0}; int n=0, i=0, j=0; n = strlen(ch1); list<char> cList(ch1, ch1+n); list<char>::iterator cIter; for(cIter=cList.begin(); cIter!=cList.end(); cIter++) { ch2[j] = *cIter; j++; } printf("%s\n%s\n", ch1, ch2); return 0; }
輸出結果為: