小编zha*_*min的帖子

在std set/map中使用double作为键的方法

在地图/集合中使用双精度作为关键字的问题是浮点精度.

有些人建议在比较函数中添加epsilon,但这意味着您的密钥将不再满足必要的严格弱排序标准.这意味着您将获得不同的集/映射,具体取决于插入元素的顺序.

如果您想基于双值聚合/组合/合并数据,并且愿意允许一定程度的舍入/ epsilon(显然,您将不得不),以下解决方案是个好主意吗?

通过将它们乘以精度因子(例如1e8)并舍入到最接近的整数(int)i+0.5(如果i> 0),将所有双精度数(我们打算作为键)转换为整数,然后创建一个关闭这些整数的集合/映射.在提取键的最终值时,将int除以精度因子以获得双值(尽管是舍入的).

c++ floating-point dictionary key set

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

C++ 构造函数线程安全

假设我在构造函数中初始化了一个成员变量向量,并且在其他几个成员函数中读取(未写入其他任何地方)该向量。我是否需要保护对向量的访问(包括在构造函数中),还是保证该对象在其他线程中使用之前将被完全初始化并刷新到主内存?

让我举个例子:

class A
{
public:
    A();
    void f1();
    void f2();
private:
    std::vector<int> v;
};

A::A()
{
    // do some setup work in v
    v.push_back(1);
}

// called from thread1
void A::f1()
{
    // some readonly work on v
    for (auto i : v) {
        // do something on i
    }
}

// called from thread2
void A::f2()
{
    // more readonly work on v
    if (v.empty()) {
        // do other work
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要在锁保护v A::A()A::f1()A::f2() …

c++ multithreading thread-safety c++11

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

设置理解不符合预期

需要帮助解释为什么此代码段不会像我期望的那样返回

>>> a = 1
>>> v = ["a", "b", "c"]
>>> {e for e in v if locals().get(e) is None}
set(['a', 'c', 'b'])
Run Code Online (Sandbox Code Playgroud)

我希望它能够返回set(['c', 'b']),就像我建立一个列表一样

>>> [e for e in v if locals().get(e) is None]
['b', 'c']
Run Code Online (Sandbox Code Playgroud)

python python-2.7 set-comprehension

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