標籤:std 匹配 bin ase nat 等於 alt else ace
一、概念
二、應用執行個體
1.進位轉換
#include <stdlib.h>#include <iostream>#include <string>#include "MyStack.h"#include "Coordinate.h"using namespace std;#define BINARY 2#define OCTONARY 8#define HEXADECIMAL 16void main ( ){ //MyStack<int> s(30); MyStack<char> s(30); char num[]="0123456789ABCDEF"; int N=1348; int mod=0; while (N!=0) { mod=N%16; s.push(num[mod]); N=N/16; } s.stackTraverse(false); /* int elem=0; for (int i=s.stackLength()-1;i>=0;i--) { s.pop(elem); cout<<num[elem]; }*/ /*while(!s.stackEmpty()) { s.pop(elem); cout<<num[elem]; }*/ system("pause"); }
2.括弧匹配
MyStack<char> s(30); //存放未匹配的括弧 MyStack<char> s1(30); //存放棧頂括弧的另一半 char str[] = "([])["; //存放待匹配文本目標,要求無空格 e.g. [()()] ([]([])) char current=0; //當前括弧需要匹配的另一半 for (int i=0;i<strlen(str);i++) { if (current!=str[i]) { s.push(str[i]); switch(str[i]) { case ‘[‘: //case 後面資料類型是int,單個字元會轉換成其ASC碼 if (current!=0) { s1.push(current); } current=‘]‘; break; case ‘(‘: if (current!=0) { s1.push(current); } current=‘)‘; break; default: cout<<"括弧不匹配."<<endl; //default後面語句可以注釋掉,因為current不等於str[i]時str[i]就會入棧,第一個棧不為零匹配就會失敗 } } else { char elem; s.pop(elem); if(!s1.pop(current)) { current=0; } } }if (s.stackEmpty()) { cout<<"括弧匹配"<<endl; } else { cout<<"括弧不匹配"<<endl; } system("pause");
資料結構C++版-棧