判断机器是大顶端还是小顶端
#include <iostream>
#include <string>
using namespace std;
#define BYTE unsigned char
//big endian or little endian
void method1()
{
unsigned int uNum,*p;
p = &uNum;
uNum = 0;
*(BYTE*)p = 0xff;
if (uNum == 0xff){
printf("Little endian!\n");
}else{
printf("Big endian!\n");
}
}
void method2()
{
union w{
int a;
char b;
}obW;
obW.a = 1;
printf("%d\n",sizeof(obW));
if (obW.b == 1){
printf("Little endian!\n");
}else{
printf("Big endian!\n");
}
}
int main()
{
method1();
method2();
return 0;
}
判断对应的序列是否为正确的出栈序列
#include <iostream>
#include <stack>
using namespace std;
bool IsPopOrder(const int * pPush, const int * pPop, int iLen)
{
bool bPopOrder = false;
if (NULL == pPush || NULL == pPop || iLen<=0){
return bPopOrder;
}
std::stack<int> stackData;
const int *pNextPop = pPop;
const int *pNextPush = pPush;
while (pNextPop-pPop < iLen)
{
while(pNextPush-pPush < iLen)
{
if (stackData.empty() || stackData.top() != *pNextPop){
stackData.push(*pNextPush);
++pNextPush;
}
if (stackData.top() == *pNextPop){
break;
}
}
if (stackData.top() != *pNextPop){
break;
}
stackData.pop();
++pNextPop;
}
if (stackData.empty() && pNextPop-pPop == iLen){
bPopOrder = true;
}
return bPopOrder;
}
int main()
{
int iArrPush[] = {1,2,3,4,5};
int iArrPop[] = {4,5,3,2,1};
bool bRes = IsPopOrder(iArrPush,iArrPop,5);
if (bRes){
cout<<"Right Order!"<<endl;
}else{
cout<<"Wrong Order!"<<endl;
}
return 0;
}
判断一个数是否为素数
#include <math.h>
bool JudgePrimeNumber(int iN)
{
for (int i=2; i<=sqrt(iN);i++)
{
if (iN%i == 0)
return false;
}
return true;
}
实现string类中默认的四个函数
#include <iostream>
#include <string>
using namespace std;
class String{
public:
//constructor
String(const char *str = NULL);
//copy constructor
String(const String & other);
//destructor
~String();
//assignment operator
String & operator=(const String &other);
const char* GetString(){return m_pData;};
private:
char *m_pData;
};
String::~String(){
delete [] m_pData;
}
String::String(const char *str){
if (NULL == str){
m_pData = new char[1];
*m_pData = '\0';
} else{
int iLen = strlen(str);
m_pData = new char[iLen+1];
strcpy(m_pData,str);
}
}
String::String(const String & other){
int iLen = strlen(other.m_pData);
m_pData = new char[iLen+1];
strcpy(m_pData,other.m_pData);
}
String & String::operator=(const String &other){
if( this == &other){ //检测自赋值
return *this;
}
if (other.m_pData){
delete[] m_pData; //释放原有的内存资源
}
int iLen = strlen(other.m_pData);
m_pData = new char[iLen+1];
strcpy(m_pData,other.m_pData);
return *this;
}
int main()
{
String s1("hello xiaojie\0");
String s2 = s1;
String s3(s1);
cout<<s1.GetString()<<endl;
cout<<s2.GetString()<<endl;
cout<<s3.GetString()<<endl;
return 0;
}