相关疑难解决方法(0)

如何在两个32位整数中存储64位整数并再次转换回来

我很确定它只是一些按位操作的问题,我只是不完全确定我应该做什么,并且所有搜索都返回"64位对32位".

c++

27
推荐指数
3
解决办法
3万
查看次数

C未定义的行为.严格别名规则或错误对齐?

我无法解释这个程序的执行行为:

#include <string> 
#include <cstdlib> 
#include <stdio.h>

typedef char u8;
typedef unsigned short u16;

size_t f(u8 *keyc, size_t len)
{
    u16 *key2 = (u16 *) (keyc + 1);
    size_t hash = len;
    len = len / 2;

    for (size_t i = 0; i < len; ++i)
        hash += key2[i];
    return hash;
}

int main()
{
    srand(time(NULL));
    size_t len;
    scanf("%lu", &len);
    u8 x[len];
    for (size_t i = 0; i < len; i++)
        x[i] = rand();

    printf("out %lu\n", f(x, len));
}
Run Code Online (Sandbox Code Playgroud)

因此,当使用带有gcc的-O3编译并使用参数25运行时,它会引发段错误.没有优化它工作正常.我已经对它进行了反汇编:它正在进行矢量化,并且编译器假定 …

c gcc strict-aliasing memory-alignment

13
推荐指数
3
解决办法
2368
查看次数

更高效的结构为unordered_map <pair <int,int>,int>

我有大约20,000,000 pair<int, int>,我需要与ints联系.我这样做了unordered_map<pair<int, int>, int>.分析我的算法表明检查条目是否存在

bool exists = myMap[make_pair(a, b)] != NULL
Run Code Online (Sandbox Code Playgroud)

是性能瓶颈.我认为从a中检索这些信息unordered_map会非常快,因为它是O(1).但如果常数很大,则恒定时间可能会很慢......

我的哈希函数是

template <>
struct tr1::hash<pair<int, int> > {
public:
        size_t operator()(pair<int, int> x) const throw() {
             size_t h = x.first * 1 + x.second * 100000;
             return h;
        }
};
Run Code Online (Sandbox Code Playgroud)

你知道我的问题有更好的数据结构吗?

显然,我不能只将信息存储在矩阵中,因此内存量不适合现有的任何计算机.我所知道的所有分布都是myMap[make_pair(a, a)]不存在的a.并且所有ints都在从0到大约20,000,000的连续范围内.

可以把它想象成20,000,000x20,000,000的稀疏矩阵,大约有20,000,000个条目但从不在主对角线上.

建议

将一vector<pair<int, int>>*(阵列Ñ预期的条目)要快?查找a将是微不足道的(只是数组的索引),然后我将迭代向量,比较对的firstb.

大新闻

我上传了原始数据,因此您可以看到结构.

c++ algorithm performance unordered-map map

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

如何在一个 64 位整数中存储和使用两个 32 位有符号整数?

首先,我想澄清一下,这个问题与问题不同:

这个问题是存储和使用,这意味着我可以做到这一点

int64_t score = make_score(-15, 15);
score += make_score(-5, 5); //I can use (add, subtract) the score
int32_t a = get_a(score);
assert(a == -20); //-15 -5 = -20
int32_t b = get_b(score);
assert(b == 20);//15 + 5= 20
Run Code Online (Sandbox Code Playgroud)

这对于一个 32 位 int 中的两个 16 位 int 是可以实现的(Stockfish 做到了这一点):

/// Score enum stores a middlegame and an endgame …
Run Code Online (Sandbox Code Playgroud)

c++ int bit-manipulation data-structures

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