小编Kri*_*ish的帖子

为什么`offset_from` 使用的指针必须从指向同一对象的指针派生?

标准库

两个指针必须派生自指向同一对象的指针。(请参见下面的示例。)

let ptr1 = Box::into_raw(Box::new(0u8));
let ptr2 = Box::into_raw(Box::new(1u8));
let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
// Make ptr2_other an "alias" of ptr2, but derived from ptr1.
let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
assert_eq!(ptr2 as usize, ptr2_other as usize);
// Since ptr2_other and ptr2 are derived from pointers to different 
// objects, computing their offset is undefined behavior, even though
// they point to the same address!
unsafe {
    let zero = ptr2_other.offset_from(ptr2); // Undefined …
Run Code Online (Sandbox Code Playgroud)

pointers rust

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

使用 zip() 对元组列表进行排序时,有时不支持“<”

我想根据堆栈溢出帖子中的第二个列表对列表进行排序。就我而言,我的代码试图按Chromo对象对它们进行排序fitness_weights,因此我尝试了链接帖子上的解决方案:

def foobar():
    ...
    chromolist = [x for _, x in sorted(zip(fitness_weights, chromolist))]
    ...
Run Code Online (Sandbox Code Playgroud)

给出错误:

TypeError: '<' not supported between instances of 'Chromo' and 'Chromo'
Run Code Online (Sandbox Code Playgroud)

为了调试我试过:

def foobar():
    ...
    try:
        chromolist = [x for _, x in sorted(zip(fitness_weights, chromolist))]
    except Exception as e:
        print(fitness_weights)
        print(chromolist)
        print([i for i in zip(fitness_weights, chromolist)])
        raise e
    print('works fine')
    ...
Run Code Online (Sandbox Code Playgroud)

输出:

works fine
works fine
works fine
works fine
works fine
works fine
works fine
works fine
works …
Run Code Online (Sandbox Code Playgroud)

python sorting python-3.x

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

标签 统计

pointers ×1

python ×1

python-3.x ×1

rust ×1

sorting ×1