C++学习记录

1. sort函数参数

cplusplus官网关于sort的英文解释

简单的说,有两种形式:带或者不带第三个参数。

// default (1)	
template <class RandomAccessIterator>  void sort (RandomAccessIterator first, RandomAccessIterator last);
// custom (2)	
template <class RandomAccessIterator, class Compare>  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

 我们先解释第二种形式(custom:定制),其第三个参数可以传入函数指针或者函数对象,这个函数有两个参数,返回的布尔类型值表示第一个参数是否排在第二个参数之前。而与大于小于之类无直接关系。

所以我们看第一种默认形式,省略第一个参数,那么就默认使用小于号,即如果一个数“小于”另一个数,那么前者在后者(在排序后的序列种的)前面。

举个栗子,下面这个sort排列的是x和y连接后的数如果小于y和x连接后的数,那么x排在前面。对应的力扣题:力扣

class Solution {
public:
    string minNumber(vector<int>& nums) {
        vector<string> strs;
        string res;
        for(int i = 0; i < nums.size(); i++)
            strs.push_back(to_string(nums[i]));
        sort(strs.begin(), strs.end(), [](string& x, string& y){ return x + y < y + x; });
        for(int i = 0; i < strs.size(); i++)
            res.append(strs[i]);
        return res;
    }
};

作者:jyd
链接:https://leetcode.cn/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/solution/mian-shi-ti-45-ba-shu-zu-pai-cheng-zui-xiao-de-s-4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

2. 堆结构

大顶堆/大根堆:堆顶元素是最大的。

c++中的priority_queue是大根堆。

下面是我对官方文档的个人理解,英文直接拷贝自文档https://cplusplus.com/reference/queue/priority_queue/

template <
    class T, 
    class Container = vector<T>,  
    class Compare = less<typename Container::value_type> 
> 
class priority_queue;

  Priority queues are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are popped from the "back" of the specific container, which is known as the top of the priority queue.

priority_queue按照container adaptor(容器适配器)的方式实现。

何为container adaptor?容器适配器中的元素在底层存储在underlying container(底层容器)中, 比如底层容器可以是vector,并且默认下就是vector,可以看模板参数的第二个。根据我的实验,priority_queue的实例不能直接调用底层容器的方法,只能使用priority_queue定义的方法。

第三个模板参数comp是一个函数指针或者函数对象,用来作为元素间比较大小的函数。comp(a,b)返回真,那么a排在b的前面,这里的“前面”不是指堆顶,而是a、b两元素在底层容器的前后关系,比如默认情况下底层容器是vector,comp是less,那么就是a比b小时排在前面。

The priority_queue uses this function to maintain the elements sorted in a way that preserves heap properties (i.e., that the element popped is the last according to this strict weak ordering). 

堆的pop函数弹出的堆顶的元素,这个堆顶的元素是“最后一个”元素。

捋一下,默认情况下底层容器是vector,比较函数是less,也就是最终形成一个升序序列,堆顶是最后一个元素,也就是最大者,那么这种情况下是一个大顶堆。

3. multiset

  • 有序
  • 元素可以重复
  • 如果multiset中已有某个元素,再加入这个元素,新元素排在旧元素之后

负数取相反数或者整数取绝对值时,注意负的有符号数中最小者没有对应的正数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值