(一)用基本的数组实现
#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; }
输出结果为:
时间: 2024-10-14 17:49:39