记录一些我老是忘记的常用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);
 当已经声明之后 可以通过sstr.str(str);把str这个字符串的内容拷贝给sstr
    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;

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值