記錄一些我老是忘記的常用C++語句

目錄

一、數據類型

(1)約整和連續操作

(2)自定義類型的小頂堆使用方法 decltype (暫時擱置)

(3)堆的日常使用方法

(4) multiset用法

二、計算語句

(1)平方:pow(x,2)  —— x^2  ;  pow(16,x) —— 16^x次方

三、日常語句

(1)sort函數自定義compare方法 和本來的方法

(2)strcpy語句

(3)string查找

(4)全排列

(5)vector不能爲空的初始化

(6)字符串和數值轉換

(7)Memset

 


一、數據類型

(1)約整和連續操作

double轉int 向下約整

double和int float一起操作 最後是double型

(2)自定義類型的小頂堆使用方法 decltype (暫時擱置)

class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        auto cmp = [](ListNode*& a, ListNode*& b) {
            return a->val > b->val;
        };
        priority_queue<ListNode*, vector<ListNode*>, decltype(cmp) > q(cmp);
        for (auto node : lists) {
            if (node) q.push(node);
        }
        ListNode *dummy = new ListNode(-1), *cur = dummy;
        while (!q.empty()) {
            auto t = q.top(); q.pop();
            cur->next = t;
            cur = cur->next;
            if (cur->next) q.push(cur->next);
        }
        return dummy->next;
    }
};

(3)堆的日常使用方法

基本類型的大頂堆使用方法:


#include <iostream>
#include <queue>
 
using namespace std;
 
int main(){
    priority_queue<int> q;
     
    for( int i= 0; i< 10; ++i ) q.push( rand() );
    while( !q.empty() ){
        cout << q.top() << endl;
        q.pop();
    }
     
    getchar();
    return 0;
}

基本類型的小頂堆使用方法:

#include <iostream>
#include <queue>
#include<xfunctional>
using namespace std;
 
int main(){
    priority_queue<int, vector<int>, greater<int> > q;小頂堆
     
    for( int i= 0; i< 10; ++i ) q.push( rand() );
    while( !q.empty() ){
        cout << q.top() << endl;
        q.pop();
    }
     
    getchar();
    return 0;
}

自定義類型的小頂堆 (跟sort不一樣 那個> < 不對勁煩死了)

#include <iostream>
#include <queue>
 
using namespace std;
 
struct Node{
    int x, y;
    Node( int a= 0, int b= 0 ):x(a), y(b) {}
};
 
bool operator<( Node a, Node b ){ 小頂堆
    if( a.x== b.x ) return a.y> b.y;
    return a.x> b.x; 
}
 
int main(){
    priority_queue<Node> q;
     
    for( int i= 0; i< 10; ++i )
    q.push( Node( rand(), rand() ) );
     
    while( !q.empty() ){
        cout << q.top().x << ' ' << q.top().y << endl;
        q.pop();
    }
     
    getchar();
    return 0;
}

#include <iostream>
#include <queue>
 
using namespace std;
 
struct Node{
    int x, y;
    Node( int a= 0, int b= 0 ):
        x(a), y(b) {}
};
 
struct cmp{
    bool operator() ( Node a, Node b ){
        if( a.x== b.x ) return a.y> b.y;小頂堆
         
        return a.x> b.x; }
};
 
int main(){
    priority_queue<Node, vector<Node>, cmp> q;
     
    for( int i= 0; i< 10; ++i )
    q.push( Node( rand(), rand() ) );
     
    while( !q.empty() ){
        cout << q.top().x << ' ' << q.top().y << endl;
        q.pop();
    }
     
    getchar();
    return 0;
}

 

想要改成大頂堆的話 就把這裏改一下:

struct cmp{
    bool operator() ( Node a, Node b ){
        if( a.x== b.x ) return a.y< b.y;大頂堆
         
        return a.x< b.x; }
};



兩種方法

bool operator<( Node a, Node b ){ 大頂堆 注意這一行的<不能改的啊
    if( a.x== b.x ) return a.y< b.y;
    return a.x< b.x; 
}

(4) multiset用法

降序和升序皆有 multiset與set的區別就是允許重複 默認是升序

// cont/mset1.cpp

   #include <iostream>
   #include <set>
   using namespace std;

   int main()
   {

       typedef multiset<int,greater<int> > IntSet;

       IntSet coll1,        // empty multiset container

       //insert elements in random order
       coll1.insert(4);
       coll1.insert(3);
       coll1.insert(5);
       coll1.insert(l);
       coll1.insert(6);
       coll1.insert(2);
       coll1.insert(5);

       //iterate over all elements and print them
       IntSet::iterator pos;
       for (pos = coll1.begin(); pos != coll1.end(); ++pos) {
           cout << *pos << ' ';
       }
       cout << endl;

       //insert 4 again and process return value
       IntSet::iterator ipos = coll1.insert(4);
       cout << "4 inserted as element "
            << distance (coll1.begin(),ipos) + 1
            << endl;

       //assign elements to another multiset with ascending order
       multiset<int> coll2(coll1.begin(),
                              coll1.end());

       //print all elements of the copy
       copy (coll2.begin(), coll2.end(),
             ostream_iterator<int>(cout," "));
       cout << endl;

       //remove all elements up to element with value 3
       coll2.erase (coll2.begin(), coll2.find(3));

       //remove all elements with value 5
       int num;
       num = coll2.erase (5);
       cout << num << " element(s) removed" << endl;

       //print all elements
       copy (coll2.begin(), coll2.end(),
             ostream_iterator<int>(cout," "));
       cout << endl;
   }

輸出:

6 5 5 4 3 2 1
4 inserted as element 5
1 2 3 4 4 5 5 6
2 element(s) removed
3 4 4 6

 

 

二、計算語句

(1)平方:pow(x,2)  —— x^2  ;  pow(16,x) —— 16^x次方

 #include <cmath>  或者 #include <math.h>

三、日常語句

(1)sort函數自定義compare方法 和本來的方法

 LeetCode 056. Merge Intervals 合併區間

    bool mySort(const Interval &a, const Interval &b) {
    return a.start < b.start;
 }

class Solution {
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        if (intervals.empty()) return {};
        sort(intervals.begin(), intervals.end(), mySort);//重點
        vector<Interval> res{intervals[0]};
        for (int i = 1; i < intervals.size(); ++i) {
            if (res.back().end < intervals[i].start) {
                res.push_back(intervals[i]);
            } else {
                res.back().end = max(res.back().end, intervals[i].end);
            }
        }   
        return res;
    }

};

這裏的mySort要寫在類外,因爲std::sort要求函數對象,或是靜態/全局函數指針,非靜態成員函數指針不能直接傳遞給std::sort

新的方法,更方便:

class Solution {
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        if (intervals.empty()) return {};
        sort(intervals.begin(), intervals.end(), [](Interval &a, Interval &b) {return a.start < b.start;});
這裏!!!直接把函數寫完了 前面加一個[]就好了 這裏return b.start>a.start也是可以的
        vector<Interval> res{intervals[0]};
        for (int i = 1; i < intervals.size(); ++i) {
            if (res.back().end < intervals[i].start) {
                res.push_back(intervals[i]);
            } else {
                res.back().end = max(res.back().end, intervals[i].end);
            }
        }   
        return res;
    }
};

(2)strcpy語句


int main()
{
	   char strDest[]="123456789"; 
      這個一定要是數組 因爲如果是指針就相當於這個指針指向一個常量了 那根本無法寫入

          char strDest[3]="12";也是可以通過的 結果都是012345678 但是不對!!

	   const char *strSrc = "012345678"; 
        這個是指針或是數組都可以 const也無所謂
	
		assert((strDest != NULL) && (strSrc != NULL));
		//char *address = strDest;
		//while ((*strDest++ = *strSrc++) != '\0');
		strcpy(strDest,strSrc);
		cout << strDest << endl; 012345678
            cout<<*strDest<<endl;  這裏就是0
		return 0;
}

(3)string查找

一般的查找 迭代器如果找不到是==s.end(); 

string語句找不到是:

s.find(c) == string::npos

(4)全排列

一個不錯的參考鏈接:https://blog.csdn.net/howardemily/article/details/68064377

頭文件: #include<algorithm>   用之前記得sort排序哦

此外,next_permutation(node,node+n,cmp)可以對結構體num按照自定義的排序方式cmp進行排序。

class Solution {
public:
    vector<vector<int>> permute(vector<int>& num) {
        vector<vector<int>> res;
        sort(num.begin(), num.end());
        res.push_back(num);
        while (next_permutation(num.begin(), num.end())) {
            res.push_back(num);
        }
        return res;
    }
};

next_permutation(v.begin() ,v.end() )

(5)vector不能爲空的初始化

if (num.empty()) return vector<vector<int>>(1, vector<int>());
 vector<vector<int>> res{{}};

(6)字符串和數值轉換

1. itoa函數
char *itoa(int value, char *string, int radix);
 
value: 待轉化的整數。
radix: 是基數的意思,即先將value轉化爲radix進制的數,範圍介於2-36,比如10表示10進制,16表示16進制。
* string: 保存轉換後得到的字符串。
返回值:
char * : 指向生成的字符串, 同*string。
備註:該函數的頭文件是"stdlib.h"
 
2. atoi
  C語言庫函數名: atoi
  功 能: 把字符串轉換成整型數
  函數說明: atoi()會掃描參數nptr字符串,檢測到第一個數字或正負符號時開始做類型轉換,之後檢測到非數字或結束符 \0 時停止轉換,返回整型數。
  原型: int atoi(const char *nptr);
  需要用到的頭文件: #include <stdlib.h>

string str="123"
int i=atoi(str.c_str());

第二種方法 用stringstream  但是很慢

一.利用stringstream類
1. 字符串到整數
    string str;
    getline(cin,str);
    stringstream sstr(str);
    int x;
    sstr >> x;(即從sstr中提取數據)
2. 整數到字符串
    stringstream sstr;
    int x;
    sstr << x;
    string str = sstr.str();
缺點:處理大量數據轉換速度較慢。stringstream不會主動釋放內存,
如果要在程序中用同一個流,需要適時地清除一下緩存(用stream.str("")和stream.clear()).
 

(7)Memset

#include<cstring>

char * number =new char[n+1];
memset(number,'0',n);
number[n]='\0';

(8) int數組

const int tableSize =256;
unsigned int hashTable[tableSize];
int * a= new int[index];
delete []a;

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章