gpt4 book ai didi

c++ - 实现一个支持 2 级外观的 C++,使用任何类型的键

转载 作者:搜寻专家 更新时间:2023-10-30 22:14:32 24 4
gpt4 key购买 nike

我需要实现一个 C++ 类来支持以下内容

数据:

键 - 字符串

子键 - 字符串/ double

值 - 字符串/ double

键和子键一起唯一标识行。

例如:

[ "key", "subkey", "value" ]

[ "cse", "a", 100 ]

[ "cse", "b", 120 ]

[ "cse", 100, 10 ]

操作:

1) 给定一个键和返回值

2) 给定一个键,返回一个 [ "subkey", "value"]

数组

我面临的问题是子键和值既可以是 double 也可以是字符串。解决这个问题的一种方法是使用一个包装类,它能够存储 double 和字符串类型。

第一级 map 将有一个字符串作为键,值将是一个 map 。

第二级映射将具有作为新包装类的键,并且值也是新包装类。

这个方法对吗?还是有更好的方法来做到这一点?

最佳答案

我使用 Boost.Variant 和 C++11 破解了一个解决方案 unordered_map .该代码是 C++11 实际应用的一个很好的示例。

需要特别注意两个hash的结合在特化std::hash<key>::operator() , 它可以有一个对散列质量的强烈影响。为了更好的实现看看boost::hash_combine ,遗憾的是还没有标准化。

一般来说,代码的作用是:定义一个特殊的键类型EqualityComparable 和 Hashable,然后在 std::unordered_map .你可以只用 Boost 而不用构建所有这些完全是 C++11。如果你既没有 Boost 也没有 C++11,那你就陷入了困境点。没有对此进行真正的测试。

#include <boost/variant.hpp>
#include <string>
#include <functional>
#include <unordered_map>
#include <iostream>

struct key {
std::string primary;
boost::variant<std::string, double> secondary;
friend bool operator==(const key& x, const key& y)
{ return x.primary == y.primary && x.secondary == y.secondary; }
};

namespace std {
template<>
struct hash<key> {
std::size_t operator()(const key& k) const
{
std::size_t first = std::hash<std::string>()(k.primary);
std::size_t second;

// check for the more likely case first
if(const std::string* s = boost::get<std::string>(&(k.secondary))) {
second = std::hash<std::string>()(*s);
} else {
const double* d = boost::get<double>(&(k.secondary));
second = std::hash<double>()(*d);
}
return first ^ ( second << 1 ); // not so fancy hash_combine
}
};

} // std


int main()
{
typedef std::unordered_map<key, boost::variant<std::string, double>> MyMap;
MyMap m = {
{{"foo", "bar"}, "foobar"},
{{"foo", 23.0}, "foo23"},
{{"nothing", 23.0}, 23.0}
};

std::cout << m[{"foo", "bar"}] << std::endl;
std::cout << m[{"foo", 23.0}] << std::endl;
std::cout << m[{"nothing", 23.0}] << std::endl;

return 0;
}

关于c++ - 实现一个支持 2 级外观的 C++,使用任何类型的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16321319/

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