小编GT *_* 77的帖子

向量转换向量中的未定义行为

为什么这段代码写了一个未定义数量的看似未初始化的整数?

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


int main()
{
    for (int i : vector<vector<int>>{{77, 777, 7777}}[0])
        cout << i << ' ';
}
Run Code Online (Sandbox Code Playgroud)

我预计输出为77 777 7777.

这段代码应该是未定义的吗?

c++

20
推荐指数
3
解决办法
1100
查看次数

为什么random.choice如此不平衡?

因此,我一直在编写一些非常随机的实验代码,结果令我感到困惑。

这是我的代码

from random import choice

class A:


    def __init__(self, l):
        parsed = iter(l)

        self.include = next(parsed) == "+"
        self.l = list(parsed)



    def get(self, l):
        rt = self.l
        if self.include:
            rt += l
        return choice(rt)



a = A("+abcd")

d = dict()
for key in "abcdef":
    d[key] = 0

for i in range(100000):
    d[a.get(["e", "f"])] += 1

print(d)
Run Code Online (Sandbox Code Playgroud)

我希望代码能输出随机但有些均匀的选择分布。像这样:

{'a': 16678, 'b': 16539, 'c': 16759, 'd': 16584, 'e': 16631, 'f': 16809}
Run Code Online (Sandbox Code Playgroud)

但是实际输出是这样的:

{'a': 3, 'b': 4, 'c': 7, 'd': 3, 'e': …
Run Code Online (Sandbox Code Playgroud)

python random

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

装饰器中声明的非局部变量没有绑定

def decorator(func):
    def returning():
        var = 1
        func()
        print(var)
    return(returning)
@decorator
def function():
    nonlocal var
    var = 5
function()
Run Code Online (Sandbox Code Playgroud)

var 在调用 func() 之前在 Returning() 函数内声明,但我收到绑定错误。

我不明白为什么会发生这种情况。

python

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

为什么 ofstream &lt;&lt; 重载在作为成员函数调用时会产生不同的结果?

下面是代码:

#include <iostream>
int main()
{
    std::cout << 'a'; // a
    operator << (std::cout, 'a'); // a
    std::cout.operator << ('a'); // 97
}
Run Code Online (Sandbox Code Playgroud)

用命令编译:

g++.exe -Wall -g -Wall -std=c++11  -c <cpp file> -o <o file>
Run Code Online (Sandbox Code Playgroud)
g++.exe <exe file> <o file>  -O0 
Run Code Online (Sandbox Code Playgroud)

aa97执行时产生输出。

似乎由于某种原因调用operator <<重载作为成员函数std::cout调用 的模板特化int,即使我通过了char. 这是正确的吗?

为什么会发生?

c++ outputstream operator-overloading char

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

为什么 abs 不在 std 中?

#include <cmath>
int abs;
int main()
{

}
Run Code Online (Sandbox Code Playgroud)

此代码引发编译错误

error: 'int abs' redeclared as different kind of symbol
note: previous declaration 'int abs(int)'
Run Code Online (Sandbox Code Playgroud)

如果我从cstdlib.

我阅读了这个文档https://en.cppreference.com/w/cpp/numeric/math/abs 其中没有提到abs将在std. 事实上,它明确提到它std::abs无处不在。

其他函数也会发生同样的事情,例如sqrt.

为什么会这样?如何在不弄乱我的命名空间的情况下使用这些函数?如果不可能,是否有 C++ 替代方案?

c++

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

标签 统计

c++ ×3

python ×2

char ×1

operator-overloading ×1

outputstream ×1

random ×1