病媒没有正常繁殖

Vector not populating properly

本文关键字:繁殖 常繁殖      更新时间:2023-10-16

我试图找出在使用线性探测公式(h(k) = k%T其中T是表大小)的指定大小的哈希表中发生碰撞之前插入的平均次数。我做了100个"实验"来计算碰撞前的平均插入次数。下面是我为一个大小为23的表编写的代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>
using namespace std;

int main()
{
    int sizeArray[7] = { 7, 11, 13, 17, 19, 23, 29 }; // ignore for now
    double resultArray[7] = { 0 }; // ignore for now
    vector<double> hashNumVec; // stores hash keys
    int hashValue = 0;
    int count = 0;
    double average;
    vector<double> resultVec;
    int randNum; 
    srand(time(NULL));
    for (int k = 0; k < 100; k++){ // 100 experiments
        randNum = rand() % 100 + 1; // generate random number
        hashValue = (randNum) % 23; // hash value for T = 23

        vector<double>::iterator it;
        it = find(hashNumVec.begin(), hashNumVec.end(), hashValue);
        if (it == hashNumVec.end()){  //no collision
            count++;
            hashNumVec.push_back(hashValue);
        }
        else 
        {
            resultVec.push_back(count); // add the amount of insertions to vector
            break;
        }

    }

    for (auto i = resultVec.begin(); i != resultVec.end(); ++i)
        cout << *i << ' ';

    return 0;
}

我希望我的向量填充100个值。它们中的每一个都是导致碰撞的插入次数的计数值。然而,当我把它打印出来的时候,它只显示向量中有一个值。我做错了什么?

EDIT:我只是想存储每次碰撞需要多少插入。比如说第一次它在碰撞前插入了6次然后在碰撞前插入了5次,在碰撞前插入了4次。等等,我想让向量读取6 5 4 ...

这是因为代码:

    {
        resultVec.push_back(count); // add the amount of insertions to vector
        break;
    }

在第一次检测到碰撞时打破for循环。所以你在resultVec中只有一个值被显示。

编辑

我希望我的向量填充100个值。

当前代码不会这样做。随机化并创建一个包含100个值的散列。然后,当检测到碰撞时,仅将碰撞计数器存储在resultVec中。100次随机化中发生100次碰撞的概率为0。

break;替换为count=0;。它将打印碰撞之间的插入次数。换句话说,在下一次碰撞发生之前,没有碰撞的插入有多少次。

EDIT2

如果您正在寻找第一个碰撞之前的插入数量,那么您需要将break替换为

count = 0;
hashNumVec.clear();

您需要清除哈希向量以及计数器,因为在每次碰撞之后,您希望从头开始测量(否则计数器将显示第二次碰撞之前的插入数量,然后是第三次,等等…)

程序检查在100次插入中是否发生冲突。它不会做100次试验来计算实现碰撞需要多少次插入。为此,您需要第二个循环:

for (int k = 0; k < 100; k++){ // 100 experiments
    for(;;) {  // Each experiment continues until the "break" statement in your else clause.
        // The loop body, exactly as you currently have it written.
    }
    count = 0; // Reset for the next experiment!
}