1. 程式人生 > >常用程式碼記錄

常用程式碼記錄

參考網路眾多資料,記錄下常用的功能。

一、IP合法性判斷

#include<iostream>
#include<string>
#include<vector>
#include<iterator>
#include<sstream>
using namespace std;

//注意:當字串為空時,也會返回一個空字串
void split(string& s, string& delim, vector<string>* ret)
{
    size_t last = 0
; size_t index=s.find_first_of(delim,last); while (index!=string::npos) { ret->push_back(s.substr(last,index-last)); last=index+1; index=s.find_first_of(delim,last); } if (index-last>0) { ret->push_back(s.substr(last,index-last)); } } bool
checkIP(string tempIP) { vector<string> str; string delim = "."; split(tempIP,delim,&str);//分割字串 if(str.size()!= 4) { return false; } else { for(vector<string>::iterator iter = str.begin(); iter!=str.end(); ++iter) { int transInt=0
; stringstream ss; ss<<(*iter); ss>>transInt; if(transInt<0||transInt>255) //判斷是否是合法的數字 { return false; } } return true; } } void isRightfulIP(string tempIP) { if(checkIP(tempIP)) { cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } } int main() { string strIP; getline(cin,strIP); isRightfulIP(strIP); }

二、去除字串2在字串1中所有字元

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <cstdlib>
using namespace std;

char * string_del_characters( char * const src, const char * const dest )
{
   int destLen = strlen(dest);
   int hashTable[256] = { 0 };
   char * p = src;
   int index = 0;
   for( int i = 0; i < destLen; i++ )
   {
      hashTable[(int)dest[i]] = 1;
   }
   while( *p != '\0' )
   {
      if( 0 == hashTable[(int)*p] )
      {
         src[index++] = *p;
      }
      p++;
   }
   src[index] = '\0';
   return src;
}

int main()
{
   char src[1024];
   char dest[1024];
   scanf("%s",src);
   scanf("%s",dest);
   char * pResult = string_del_characters( src, dest );
   std::cout << pResult << std::endl;
}

三、根據中心座標找最近距離

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <cmath>
using namespace std;

int main() {
    vector<int> sets;
    string s;
    getline(cin, s);
    stringstream sstr(s);
    string token;
    //輸入字串,根據,號分割  
    while (getline(sstr, token, ',')) {
        sets.push_back(atoi(token.c_str()));
    }   
    int src_x = sets[0];
    int src_y = sets[1];
    int n = sets[2];
    if (n == 0) {
        cout << "(" << src_x << "," << src_y << ")" << endl;
        return 0;
    }
    float minDistance = 128 * 2;
    vector<int> npc(2 * n, 0);
    for (int i = 0; i < 2 * n; ++i) {
        npc[i] = sets[i + 3];
    }
    int index;
    //求座標距離
    for (int i = 0; i < 2 * n; i += 2) {
float distance = sqrtf(pow(npc[i] - src_x, 2) + pow(npc[i + 1] - src_y, 2));
        if (distance < minDistance) {
            minDistance = distance;
            index = i;
        }
    }
    cout << "(" << npc[index] << "," << npc[index + 1] << ")" << endl;  
    return 0;
}

四、根據前序遍歷和中序遍歷求後序

/*************************************************************************mZ
    > Author: FengXin
    > Mail: [email protected]
    > Created Time: 2016年10月27日 星期四 20時01分43秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<sys/signal.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<fcntl.h>

typedef struct node
{
    char data;    //結點資料
    struct node *Lchild;    //左孩子
    struct node *Rchild;    //右孩子
}tree;   //樹的結點


int  Lchild_len(char insequence[20],char root_data) //得到左孩子的長度
{
    int len=strlen(insequence);
    int i=0;
    int sum=0;  //記錄左孩子長度
    while(insequence[i]!=root_data)
    {
        i++;
        sum++;
    }
    return sum;
}

int Rchild_len(char insequence[20],char root_data)  //得到右孩子的長度
{
    int i=0;
    int sum=0;   //記錄右孩子長度
    while(insequence[i]!='\0'&&insequence[i++]!=root_data);
    while(insequence[i]!='\0')
    {
        sum++;
        i++;
    }
    return sum;
}

tree* create_tree(char presequence[20],char insequence[20]) //建立二叉樹
{
    tree* temp=(tree*)malloc(sizeof(tree));   //建立結點
    int L_len,R_len;      //儲存左右孩子長度
    char L_presequence[20],L_insequece[20];   //建立左孩子時傳入的左孩子的前序串和中序串
    char R_presequence[20],R_insequece[20];   //建立右孩子時傳入的右孩子的前序串和中序串
    L_presequence[0]=L_insequece[0]=R_presequence[0]=R_insequece[0]='\0';
    if(strlen(presequence)!=0&&strlen(insequence)!=0)  //傳入的序列串非空
    {
        temp->data=presequence[0];     //根結點資料賦值
        L_len=Lchild_len(insequence,presequence[0]);  //獲得孩子的長度
        R_len=Rchild_len(insequence,presequence[0]);
        strncpy(L_presequence,presequence+1,L_len);    //得到要遞迴建立孩子時要傳入的前序遍歷串和中序遍歷串
        *(L_presequence+L_len)='\0';              //字串末尾加上'\0'
        strncpy(R_presequence,presequence+L_len+1,R_len);
        *(R_presequence+R_len)='\0';
        strncpy(L_insequece,insequence,L_len);
        *(L_insequece+L_len)='\0';
        strncpy(R_insequece,insequence+L_len+1,R_len);
        *(R_insequece+R_len)='\0';
        temp->Lchild=create_tree(L_presequence,L_insequece);   //遞迴建立左子樹
        temp->Rchild=create_tree(R_presequence,R_insequece);   //遞迴建立右子樹
        return temp;    //返回結點地址
    }
    else    //若根結點無孩子,則返回空指標
    {
        return NULL;
    }

}

void postorder(tree *root)  //後序遍歷樹輸出
{
    if(root!=NULL)
    {
        postorder(root->Lchild);
        postorder(root->Rchild);
        printf("%3c",root->data);           
    }
    else
    return;

}

int main()
{
    char presequence[20];  //存先序序列
    char insequence[20];   //存中序序列
    tree *root;

    printf("請輸入先序序列\n");
    scanf("%s",presequence);
    printf("請輸入中序序列\n");
    scanf("%s",insequence);
    root=create_tree(presequence,insequence);
    printf("建立二叉樹成功\n");
    printf("後序遍歷輸出為:\n");
    postorder(root);
    printf("\n");

}

五、實現memcpy函式

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <cstdlib>
using namespace std;


char *my_memcpy(char *dst, const char* src, int cnt)
{
   if(dst == NULL || src == NULL) return NULL;
    char *ret = dst; 
    if (dst >= src && dst <= src+cnt-1) //記憶體重疊,從高地址開始複製
    {
        dst = dst+cnt-1;
        src = src+cnt-1;
        while (cnt--)
            *dst-- = *src--;
    }
    else    //正常情況,從低地址開始複製
    {
        while (cnt--)
            *dst++ = *src++;
    }
    return ret;
}

char * str_copy(char *dst,const char *src)
{
    if(dst == NULL || src == NULL) return NULL;
    char *ret = dst;
    my_memcpy(dst, src, strlen(src)+1);
    return ret;
}



int main()
{
   char src[1024];
   char dest[1024];
   scanf("%s",src);
  // scanf("%s",dest);
   char * pResult = str_copy(dest,  src );
   std::cout << pResult << std::endl;
}

六、對學生的若干科成績進行排序

Alay 80 90
Bob 95 99 88
Cally 88 90

#include <iostream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;


//對學生的若干科成績進行排序
struct students{
    string name;
    int avg;
};

bool comp_as_int(students objA, students objB)
{
    return (objA.avg>objB.avg);
}


int main() {

   vector<students> vec;
   students obj;

   string inputstr;
    while(getline(cin,inputstr))
    {
       //inputstr:i  am a  student
       //cout<<inputstr<<endl;

       istringstream iss;
       iss.str(inputstr);
       string tempstr;
       //根據空格分割讀取string
       int i=0;
       double sum = 0;
       while(iss>>tempstr)
       {
           if(i==0)
           {
               // cout<<tempstr<<endl;
                obj.name = tempstr;
           }
           else
           {
               //cout<<atoi(tempstr.c_str())<<endl;
               sum += atoi(tempstr.c_str());
           }
           i++;
       }
       double x = sum/(i-1);
       //四捨五入取整
       int avg = (int)(x+0.5)>(int)x?(int)x+1:(int)x;
       obj.avg = avg;
       vec.push_back(obj);
    }


    //stable_sort是穩定排序。
    sort(vec.begin(), vec.end(), comp_as_int);
    for (vector<students>::iterator it = vec.begin(); it != vec.end(); it++)
        cout << (*it).name << " "<<(*it).avg<<endl;
    cout << endl;

    return 0;
}