gpt4 book ai didi

c++ - 无法遍历 boost 无序 HashMap

转载 作者:行者123 更新时间:2023-11-28 02:54:42 24 4
gpt4 key购买 nike

我正在使用 boost 无序 HashMap ,但我很难遍历哈希表中的所有键。

#include <vector>
#include <iostream>
#include <boost/unordered_map.hpp>
#include <boost/foreach.hpp>

struct Record
{
char *data;

};

typedef boost::unordered_map<std::string, std::vector<Record*> > MAP;

struct OuterRelation
{
short num_keys;
short join_key_ndx;
MAP hash_table;
};


Record *new_record = malloc(sizeof(Record));
new_record->data = "some string";
char *key = new_record->data;
(outer_relation->hash_table)[key].push_back(new_record);

/* print all keys in the hash table */
BOOST_FOREACH(MAP::value_type pair, outer_relation->hash_table)
{
std::string key = pair.first;
...
}

程序在 foreach 循环处失败。我添加到哈希表中的元素有问题吗?

最佳答案

因为这是 C++ 停止使用 malloc 。 (C++ 使用 newdelete 。虽然:也不要使用它们。使用 std::make_unique 和可能的 std::make_sharedstd::vector<T> )。


话虽如此,原因如下:C 没有类。 C 只有 POD 类型 struct秒。

只要您在 C++ 代码中保证这一点,就可以“摆脱”C 主义。这是一个 C++ 通用函数,它通过检查 执行 malloc 技巧:

template <typename T, typename... Args>
T* make_memory_leak(Args&&... args) {
static_assert(std::is_pod<T>::value, "undefined behaviour for non-POD types");

T* raw = static_cast<T*>(malloc(sizeof(T)));

static_assert(boost::proto::is_aggregate<T>::value, "aggregate initialization required");
*raw = { std::forward<Args>(args)... };

return raw;
}

所以现在你可以说

auto record_ptr = make_memory_leak<Record>("some string");

你将拥有相当于

Record* record_ptr = static_cast<Record*>(malloc(sizeof(Record)));
*record_ptr = { "some string" }; // aggregate initialization

所以,这是您的测试代码,有效: Live on Coliru

#include <vector>
#include <iostream>
#include <boost/unordered_map.hpp>
#include <boost/foreach.hpp>
#include <boost/proto/traits.hpp>
#include <cstdlib>

struct Record {
char const* data;
};

typedef boost::unordered_map<std::string, std::vector<Record*> > MAP;

struct OuterRelation
{
short num_keys;
short join_key_ndx;
MAP hash_table;
};

template <typename T, typename... Args>
T* make_memory_leak(Args&&... args) {
static_assert(std::is_pod<T>::value, "undefined behaviour for non-POD types");

T* raw = static_cast<T*>(malloc(sizeof(T)));

static_assert(boost::proto::is_aggregate<T>::value, "aggregate initialization required");
*raw = { std::forward<Args>(args)... };

return raw;
}

int main()
{
auto outer_relation = std::make_shared<OuterRelation>();
for (auto key : { "some string", "some other string", "which", "by the way", "are", "const char(&)[]" })
outer_relation->hash_table[key].push_back(make_memory_leak<Record>(key));

/* print all keys in the hash table */
BOOST_FOREACH(MAP::value_type pair, outer_relation->hash_table)
{
std::cout << pair.first << "\n";
}
}

关于c++ - 无法遍历 boost 无序 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22271406/

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