C++做题总结

1.auto函数

https://www.cnblogs.com/QG-whz/p/4951177.html

auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型

    int a = 10;
    auto au_a = a;//自动类型推断,au_a为int类型
    cout << typeid(au_a).name() << endl;

答案:int

注意事项

    auto a4 = 10, a5 = 20, a6 = 30;//正确
    auto b4 = 10, b5 = 20.0, b6 = 'a';//错误,没有推导为同一类型
//如果初始化表达式为const或volatile(或者两者兼有),则除去const/volatile语义。
    const int a1 = 10;
    auto  b1= a1; //b1的类型为int而非const int(去除const)
    const auto c1 = a1;//此时c1的类型为const int
    b1 = 100;//合法
    c1 = 100;//非法

//如果auto关键字带上&号,则不去除const语意。
        const int a2 = 10;
    auto &b2 = a2;//因为auto带上&,故不去除const,b2类型为const int
    b2 = 10; //非法
//初始化表达式为数组时,auto关键字推导类型为指针
        int a3[3] = { 1, 2, 3 };
    auto b3 = a3;
    cout << typeid(b3).name() << endl;
//int *

//若表达式为数组且auto带上&,则推导类型为数组类型。
    int a7[3] = { 1, 2, 3 };
    auto & b7 = a7;
    cout << typeid(b7).name() << endl;
//int [3]
//auto仅仅是一个占位符,它并不是一个真正的类型,不能使用一些以类型为操作数的操作符,如sizeof或者typeid。
    cout << sizeof(auto) << endl;//错误
    cout << typeid(auto).name() << endl;//错误

2.equal_range函数+distance函数

class Solution {
public:
    int maximumCount(vector<int>& nums) {
        auto [a, b] = equal_range(nums.begin(), nums.end(), 0);
        return max(
            distance(nums.begin(), a),
            distance(b, nums.end())
        );
    }
};

这段代码使用了C++的equal_range函数来查找一个有序序列nums中值为0的元素的范围。equal_range函数返回一个pair对象,其中包含了两个迭代器,第一个迭代器指向第一个等于0的元素,第二个迭代器指向第一个大于0的元素。

代码中将返回的pair对象解构成两个变量a和b,其中a指向第一个等于0的元素,b指向第一个大于0的元素。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值