C++ 使用标准库中的堆(堆内内容需要改变)-priority_queue的pop报错"invalid heap"

在使用C++标准库的`priority_queue`时遇到'invalid heap'错误。问题源于修改堆中元素导致。解决方案是使用`vector`配合`make_heap()`和`pop_heap()`实现。在Dijkstra算法中,为优化效率,用最小堆存储最小权边。详细代码示例展示了如何用vector创建和操作最小堆。

编程时在使用标准库的priority_queue的pop时报错"invalid heap"。

查阅了很久的资料,在知乎ywq109的提问找到了解决方案,这里整理一下完整地写出来。

我遇到的这个问题主要产生的原因是在使用优先队列时,修改了堆中指针所指向地址的数据,造成出错。具体的原因我也不是很了解,应该是内部函数的实现的问题。(具体的应用情景是我在写Dijkstra的算法中要得到最小权边的时候用到最小堆来提高算法效率)

解决办法是用vector实现,具体写法如下:

	//data是要用堆处理的数组
	void deemo(W data[]) {
		auto cmp = [](W* &x, W* &y) {return *x > *y; };//实现最小堆的比较函数
		vector<W*> heap;//最小堆

		//初始化
		for (int i = 0; i < size; i++) {
			data[i] = defaultValue;
			heap.push_back(&data[i]);//将数组每一位的地址存入堆
		}

		make_heap(heap.begin(), heap.end(), cmp);//整理堆

		W *temp = nullptr;
		int minp = 0;
		for (int i = 0; i < size - 1; i++) {//假设要实现的操作

                        //更新 在另一个项目中使用时遇到了问题
                        //需要加上这一行代码,但是加上之后时间消耗会变大
                        //理论上应该不用的 不知道为什么
                        make_heap(heap.begin(), heap.end(
// 创建I2C总线句柄(可选) i2c_master_bus_handle_t PCA9557_I2C_CreateMasterBus(i2c_port_num_t i2c_port, gpio_num_t sda_io_num, gpio_num_t scl_io_num) { // I2C-主机总线配置 i2c_master_bus_config_t i2c_mst_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = i2c_port, .scl_io_num = scl_io_num, .sda_io_num = sda_io_num, .glitch_ignore_cnt = 7, .flags.enable_internal_pullup = true, }; // I2C-主机总线句柄创建 i2c_master_bus_handle_t bus_handle = malloc(sizeof(i2c_master_bus_handle_t)); ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle)); return bus_handle; } esp_err_t i2c_new_master_bus(const i2c_master_bus_config_t *bus_config, i2c_master_bus_handle_t *ret_bus_handle) { #if CONFIG_I2C_ENABLE_DEBUG_LOG esp_log_level_set(TAG, ESP_LOG_DEBUG); #endif esp_err_t ret = ESP_OK; i2c_master_bus_t *i2c_master = NULL; i2c_port_num_t i2c_port_num = bus_config->i2c_port; ESP_RETURN_ON_FALSE(bus_config, ESP_ERR_INVALID_ARG, TAG, "invalid argument"); ESP_RETURN_ON_FALSE((bus_config->i2c_port < SOC_I2C_NUM || bus_config->i2c_port == -1), ESP_ERR_INVALID_ARG, TAG, "invalid i2c port number"); ESP_RETURN_ON_FALSE(GPIO_IS_VALID_GPIO(bus_config->sda_io_num) && GPIO_IS_VALID_GPIO(bus_config->scl_io_num), ESP_ERR_INVALID_ARG, TAG, "invalid SDA/SCL pin number"); #if !SOC_I2C_SUPPORT_SLEEP_RETENTION ESP_RETURN_ON_FALSE(bus_config->flags.allow_pd == 0, ESP_ERR_NOT_SUPPORTED, TAG, "not able to power down in light sleep"); #endif // SOC_I2C_SUPPORT_SLEEP_RETENTION i2c_master = heap_caps_calloc(1, sizeof(i2c_master_bus_t) + 20 * sizeof(i2c_transaction_t), I2C_MEM_ALLOC_CAPS); ESP_RETURN_ON_FALSE(i2c_master, ESP_ERR_NO_MEM, TAG, "no memory for i2c master bus"); ESP_GOTO_ON_ERROR(i2c_acquire_bus_handle(i2c_port_num, &i2c_master->base, I2C_BUS_MODE_MASTER), err, TAG, "I2C bus acquire failed"); i2c_port_num = i2c_master->base->port_num; i2c_hal_context_t *hal = &i2c_master->base->hal; i2c_master->base->scl_num = bus_config->scl_io_num; i2c_master->base->sda_num = bus_config->sda_io_num; i2c_master->base->pull_up_enable = bus_config->flags.enable_internal_pullup; if (i2c_master->base->pull_up_enable == false) { ESP_LOGW(TAG, "Please check pull-up resistances whether be connected properly. Otherwise unexpected behavior would happen. For more detailed information, please read docs"); } ESP_GOTO_ON_ERROR(i2c_param_master_config(i2c_master->base, bus_config), err, TAG, "i2c configure parameter failed"); if (!i2c_master->base->is_lp_i2c) { I2C_CLOCK_SRC_ATOMIC() { i2c_ll_set_source_clk(hal->dev, i2c_master->base->clk_src); } } #if SOC_LP_I2C_SUPPORTED else { soc_periph_lp_i2c_clk_src_t clk_srcs[] = SOC_LP_I2C_CLKS; bool lp_clock_match = false; for (int i = 0; i < sizeof(clk_srcs) / sizeof(clk_srcs[0]); i++) { if ((int)clk_srcs[i] == (int)i2c_master->base->clk_src) { /* Clock source matches. Override the source clock type with the user configured value */ lp_clock_match = true; break; } } ESP_GOTO_ON_FALSE(lp_clock_match, ESP_ERR_NOT_SUPPORTED, err, TAG, "the clock source does not support lp i2c, please check"); LP_I2C_SRC_CLK_ATOMIC() { lp_i2c_ll_set_source_clk(hal->dev, i2c_master->base->clk_src); } } #endif i2c_master->bus_lock_mux = xSemaphoreCreateBinaryWithCaps(I2C_MEM_ALLOC_CAPS); ESP_GOTO_ON_FALSE(i2c_master->bus_lock_mux, ESP_ERR_NO_MEM, err, TAG, "No memory for binary semaphore"); xSemaphoreGive(i2c_master->bus_lock_mux); i2c_master->cmd_semphr = xSemaphoreCreateBinaryWithCaps(I2C_MEM_ALLOC_CAPS); ESP_GOTO_ON_FALSE(i2c_master->cmd_semphr, ESP_ERR_NO_MEM, err, TAG, "no memory for i2c semaphore struct"); i2c_master->event_queue = xQueueCreateWithCaps(1, sizeof(i2c_master_event_t), I2C_MEM_ALLOC_CAPS); ESP_GOTO_ON_FALSE(i2c_master->event_queue, ESP_ERR_NO_MEM, err, TAG, "no memory for i2c queue struct"); portENTER_CRITICAL(&i2c_master->base->spinlock); i2c_ll_clear_intr_mask(hal->dev, I2C_LL_MASTER_EVENT_INTR); portEXIT_CRITICAL(&i2c_master->base->spinlock); if (bus_config->intr_priority) { ESP_RETURN_ON_FALSE(1 << (bus_config->intr_priority) & I2C_ALLOW_INTR_PRIORITY_MASK, ESP_ERR_INVALID_ARG, TAG, "invalid interrupt priority:%d", bus_config->intr_priority); } #if I2C_USE_RETENTION_LINK if (bus_config->flags.allow_pd != 0) { i2c_create_retention_module(i2c_master->base); } #endif // I2C_USE_RETENTION_LINK xSemaphoreTake(i2c_master->bus_lock_mux, portMAX_DELAY); SLIST_INIT(&i2c_master->device_list); xSemaphoreGive(i2c_master->bus_lock_mux); // Initialize the queue if (bus_config->trans_queue_depth) { ESP_LOGW(TAG, "Please note i2c asynchronous is only used for specific scenario currently. It's experimental for other users because user cannot get bus error from API. And It's not compatible with ``i2c_master_probe``. If user makes sure there won't be any error on bus and tested with no problem, this message can be ignored."); i2c_master->async_trans = true; i2c_master->sent_all = true; i2c_master->trans_finish = true; i2c_master->new_queue = true; i2c_master->queue_size = bus_config->trans_queue_depth; i2c_master->queues_storage = (uint8_t*)heap_caps_calloc(bus_config->trans_queue_depth * I2C_TRANS_QUEUE_MAX, sizeof(i2c_transaction_t), I2C_MEM_ALLOC_CAPS); ESP_RETURN_ON_FALSE(i2c_master->queues_storage, ESP_ERR_NO_MEM, TAG, "no mem for queue storage"); i2c_transaction_t **pp_trans_desc = (i2c_transaction_t **)i2c_master->queues_storage; for (int i = 0; i < I2C_TRANS_QUEUE_MAX; i++) { i2c_master->trans_queues[i] = xQueueCreate(bus_config->trans_queue_depth, sizeof(i2c_transaction_t)); pp_trans_desc += bus_config->trans_queue_depth; // sanity check assert(i2c_master->trans_queues[i]); } i2c_transaction_t trans_pre = {}; for (int i = 0; i < bus_config->trans_queue_depth ; i++) { trans_pre = i2c_master->i2c_trans_pool[i]; ESP_RETURN_ON_FALSE(xQueueSend(i2c_master->trans_queues[I2C_TRANS_QUEUE_READY], &trans_pre, 0) == pdTRUE, ESP_ERR_INVALID_STATE, TAG, "ready queue full"); } i2c_master->i2c_async_ops = (i2c_operation_t(*)[I2C_STATIC_OPERATION_ARRAY_MAX])heap_caps_calloc(bus_config->trans_queue_depth, sizeof(*i2c_master->i2c_async_ops), I2C_MEM_ALLOC_CAPS); ESP_RETURN_ON_FALSE(i2c_master->i2c_async_ops, ESP_ERR_NO_MEM, TAG, "no mem for operations"); i2c_master->ops_prepare_idx = 0; } int isr_flags = I2C_INTR_ALLOC_FLAG; if (bus_config->intr_priority) { isr_flags |= 1 << (bus_config->intr_priority); } ret = esp_intr_alloc_intrstatus(i2c_periph_signal[i2c_port_num].irq, isr_flags, (uint32_t)i2c_ll_get_interrupt_status_reg(hal->dev), I2C_LL_MASTER_EVENT_INTR, i2c_master_isr_handler_default, i2c_master, &i2c_master->base->intr_handle); ESP_GOTO_ON_ERROR(ret, err, TAG, "install i2c master interrupt failed"); atomic_init(&i2c_master->status, I2C_STATUS_IDLE); i2c_ll_master_set_filter(hal->dev, bus_config->glitch_ignore_cnt); xSemaphoreGive(i2c_master->cmd_semphr); *ret_bus_handle = i2c_master; s_platform.handle[i2c_port_num] = i2c_master; return ESP_OK; err: if (i2c_master) { i2c_master_bus_destroy(i2c_master); } return ret; } 分析代码问题
最新发布
10-10
编译错误. 5123.cpp: In function 'std::vector<std::basic_string<char> > dijkstra(const std::vector<std::vector<int> >&, const std::vector<std::basic_string<char> >&, const string&, const string&)': 5123.cpp:19:67: error: wrong number of template arguments (0, should be 1) priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq; ^ In file included from /usr/include/c++/4.8.2/string:48:0, from /usr/include/c++/4.8.2/bits/locale_classes.h:40, from /usr/include/c++/4.8.2/bits/ios_base.h:41, from /usr/include/c++/4.8.2/ios:42, from /usr/include/c++/4.8.2/ostream:38, from /usr/include/c++/4.8.2/iostream:39, from 5123.cpp:1: /usr/include/c++/4.8.2/bits/stl_function.h:222:12: error: provided for 'template<class _Tp> struct std::greater' struct greater : public binary_function<_Tp, _Tp, bool> ^ 5123.cpp:19:68: error: template argument 3 is invalid priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq; ^ 5123.cpp:19:73: error: invalid type in declaration before ';' token priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq; ^ 5123.cpp:23:8: error: request for member 'emplace' in 'pq', which is of non-class type 'int' pq.emplace(0, src_idx); ^ 5123.cpp:25:16: error: request for member 'empty' in 'pq', which is of non-class type 'int' while (!pq.empty()) { ^ 5123.cpp:26:14: error: expected unqualified-id before '[' token auto [d, u] = pq.top(); ^ 5123.cpp:27:12: error: request for member 'pop' in 'pq', which is of non-class type 'int' pq.pop(); ^ 5123.cpp:28:13: error: 'd' was not declared in this scope if (d > dist[u]) continue; ^ 5123.cpp:28:22: error: 'u' was not declared in this scope if (d > dist[u]) continue; ^ 5123.cpp:31:23: error: 'u' was not declared in this scope if (graph[u][v] != INT_MAX && d + graph[u][v] < dist[v]) { ^ 5123.cpp:31:43: error: 'd' was not declared in this scope if (graph[u][v] != INT_MAX && d + graph[u][v] < dist[v]) { ^ 5123.cpp:34:20: error: request for member 'emplace' in 'pq', which is of non-class type 'int' pq.emplace(dist[v], v); ^ 5123.cpp:50:37: error: 'reverse' was not declared in this scope reverse(path.begin(), path.end()); ^ 5123.cpp: In function
05-13
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值