小编eli*_*inx的帖子

我应该检查函数的每个参数以确保函数正常运行吗?

我注意到标准 c 库包含几个不检查输入参数(是否为 NULL)的字符串函数,例如 strcmp:

int strcmp(const char *s1, const char *s2)
{
    for ( ; *s1 == *s2; s1++, s2++)
    if (*s1 == '\0')
        return 0;
    return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}
Run Code Online (Sandbox Code Playgroud)

还有许多其他人没有进行相同的验证。这是一个好的做法吗?

在其他库中,我看到他们检查每个参数,如下所示:

int create_something(int interval, int mode, func_t cb, void *arg, int id)
{
    if (interval == 0) return err_code_1;
    if (valid(mode))   return err_code_2;
    if (cb == NULL)    return err_code_3;
    if (arg == NULL)   return err_code_4;
    if (id == 0) …
Run Code Online (Sandbox Code Playgroud)

c api parameter-passing

6
推荐指数
1
解决办法
1685
查看次数

为什么以下代码段会加快代码速度?

我在LeetCode上解决了搜索插入位置问题.以下代码运行所有测试用例大约需要9毫秒.

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int lo = 0, hi = nums.size() - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (target < nums[mid]) {
                hi = mid - 1;
            } else if (target > nums[mid]){
                lo = mid + 1;
            } else {
                return mid;
            }
        }
        return lo;
    }
};
Run Code Online (Sandbox Code Playgroud)

当我查看其他人的最佳答案时,我发现了一个奇怪的代码片段.当我将代码段复制粘贴到我的答案中时,上面相同的代码只需要4毫秒,这比其他解决方案的近99%快.任何人都可以解释加快速度吗?该片段如下:

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

static vector<int> nums=[](){ …
Run Code Online (Sandbox Code Playgroud)

c++ lambda c++11

6
推荐指数
1
解决办法
883
查看次数

主要论点?

我知道主要的签名是:

int main(int argc, char **argv);
Run Code Online (Sandbox Code Playgroud)

但我真的不知道为什么像这样的主要也会起作用:

main(a){}
Run Code Online (Sandbox Code Playgroud)

这是什么'做'?为什么编译器不显示错误?因为我在使用它之前没有声明'a'.

c program-entry-point arguments

3
推荐指数
1
解决办法
74
查看次数

无限的序列号生成器不能在python中工作?

我正在尝试实现一个可以生成无限数字的自然数生成器,我的代码:

def nature():
    s = 0
    while True:
        yield s
        s += 1
Run Code Online (Sandbox Code Playgroud)

当我使用时next(nature()),我得到一个0的序列,为什么这个?以及如何解决它?

>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0
Run Code Online (Sandbox Code Playgroud)

python generator

1
推荐指数
1
解决办法
46
查看次数