gpt4 book ai didi

c++ - HashMap 以找到添加到给定总和的一对

转载 作者:行者123 更新时间:2023-11-30 02:38:35 34 4
gpt4 key购买 nike

我正在尝试学习如何在 C++ 中使用散列映射,但在将随机生成的数组放入散列映射时遇到了问题,其中键和 vector 的整数作为值(用于数组中的重复值)。我还没有对总和进行编码,因为我想确保我可以先将数组输入 HashMap 中。

当我用我的显示函数输出 HashMap 时,我得到了

        Total size: 1
Index in H Number
key: 0 values: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

我创建的数组有 15 个值,范围从 1-10,所以有重复,因此需要 vector 。我不确定我做错了什么,所以欢迎任何形式的指导。

#include <iostream>   
#include <time.h>
#include <fstream>
#include <map>
#include <cstdlib>
#include <iomanip>
#include <vector>

void display(std::map <int, std::vector<int> > hash);

int main(){
srand (time(NULL));
int temp;
int tempCount = 1;
int count = 0;
int number;
int k = 10; //sum for pairs in an array

//create array for testing
int size = 15;
int foo[size] = {};
for(int i = 0; i < size; ++i){
foo[i] = ((double)rand() * (10 - 1) / (double)RAND_MAX + 1);
}
//print array:
for(int i = 0; i < size; ++i){
std::cout << foo[i] << std::endl;
}

//Find pairs in an array whose sum is equal to ten using hash map
std::map <int, std::vector<int> > hash;
const std::pair<int, int> pairs[size];
for(int i = 0; i < size; i++){
std::make_pair(pairs[foo[i]] , i);
}

const int N = sizeof(pairs) / sizeof(pairs[0]);
for(int i = 0; i < N; ++i){
const int& key = pairs[i].first;
const int value = pairs[i].second;
hash[key].push_back(value);
}
display(hash);
}

void display (std::map <int, std::vector<int> > hash)
{
std::cout << "\tTotal size: " << hash.size() << std::endl; /* Output the size */
/* Create an iterator, much like vector iterators */
std::map <int, std::vector<int> >::iterator it;
for (it = hash.begin(); it != hash.end(); it++){
/* Output first (which is index) and second (which is the element) */

const int& key = it->first ;
std::cout << "key: " << key << " values: ";

const std::vector<int>& values = it->second ;
for(std::size_t i = 0; i < values.size(); ++i)
std::cout << values[i] << ' ';
std::cout << '\n';
}

std::cout << std::endl; /* Print a new line */
}

最佳答案

通过改变:

const std::pair<int, int> pairs[size];
for(int i = 0; i < size; i++){
std::make_pair(pairs[foo[i]] , i);
}

收件人:

std::pair<int, int> pairs[size];
for(int i = 0; i < size; i++){
pairs[i] = std::make_pair(foo[i] , i);
}

应该解决最初的问题。

注意:我删除了 const 以便可以修改对值,否则它们将全部保留为 (0,0)。

关于c++ - HashMap 以找到添加到给定总和的一对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30699187/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com