尴尬的面试

昨天捞到一个面试,下班直接钻进一个会议室线上电话面试 + 共享屏幕敲代码。

1. C++ stl问题

声明一个空的vector,先后调用 reverse(10) 与 resize(10),请问 size 的返回值分别多少?

我只记得 capacity 返回可容纳元素的个数,size 返回实际容纳的元素,答曰0。

结果测试了以下,并非如此,g

#include <iostream>
#include <vector>
int main()
{
    std::vector<int> vecs;
    vecs.reserve(10);
    std::cout<<vecs.size()<<std::endl;
    std::cout<<vecs.capacity()<<std::endl;

    vecs.resize(10);
    std::cout<<vecs.size()<<std::endl;
    std::cout<<vecs.capacity()<<std::endl;
    return 0;
}

/* 输出
0
10
10
10

reserve 很清楚;而 resize,这里引用 https://cplusplus.com/reference/vector/vector/resize/ 的说法:

If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.

可见 resize 操作为 空的vector 尾后添加了足量的 值初始化 的元素,测试代码:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
    std::vector<int> vecs;

    vecs.resize(10);
    std::cout<<vecs.size()<<std::endl;
    std::cout<<vecs.capacity()<<std::endl;
    std::copy(vecs.cbegin(),vecs.cend(),std::ostream_iterator<int>(std::cout," "));
    std::cout<<std::endl;
    return 0;
}

/* 输出
10
10
0 0 0 0 0 0 0 0 0 0 

注: resize 也有这种用法, resize( isize, ival )。

2. 为什么构造函数不能为虚函数

主要原因:虚函数的调用基于虚函数表机制,即每个对象的空间内含有一个 虚函数表指针,而构造函数调用时,对象还未构造完全,无法根据虚表指针去调用虚函数。

3. 敲代码:反转链表

离谱,今天又重新写了一下 ok 了,似乎与昨天代码的主要区别在于 添加传入空链表的判断 与 实际头结点 next 指针置空的操作,一共享屏幕就有点方了 。。。 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (nullptr == head) return head;

        ListNode *vhead = new ListNode();
        vhead -> next = head;

        ListNode *pre = vhead;
        ListNode *cur = pre -> next;
        ListNode *post = nullptr;

        while(cur)
        {
            post = cur -> next;
            cur -> next = pre;
            pre = cur;
            cur = post;
        }

        delete vhead;
        vhead = nullptr;
        head -> next = nullptr;

        return pre;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值