我要制表
struct object {
std::string unique_name;
some_type more_data;
other_type member_functions() const; // many such member functions
};
使用 unique_name
作为索引。不幸的是,我不能使用
using object_table = std::unordered_set<object>;
因为无法搜索给定名称的对象,如 object_table::find()
只允许类型为 object
的搜索键:
class objects {
object_table _table;
public:
object const&operator[](std::string const&name) const
{
// cannot be implemented using object_table::find()
}
};
那我该怎么办呢?
到目前为止我尴尬的解决方案是
using object_table = std::unordered_map<std::string, some_type>;
struct object : object_table::value_type
{
std::string const&name() const { return first; }
other_type member_functions() const;
private:
using object_table::value_type::first;
using object_table::value_type::second;
};
class objects {
object_table _table;
public:
object const&operator[](std::string const&name) const
{
auto it = _table.find(name);
if(it == _table.end())
throw runtime_error("cannot find object '"+name+'\'');
return *static_cast<const object*>(std::addressof(*it)); // is cast legal?
}
};
这以修补的价格工作 object
从 std::pair<std::string, some_type>
以一种繁琐的方式在一起.
最佳答案
由于每个对象的名称都是唯一的,因此您可以只使用 unique_name
的哈希值作为对象的哈希值。使用
namespace std
{
template<> struct hash<object>
{
typedef object argument_type;
typedef std::size_t result_type;
result_type operator()(argument_type const& o) const noexcept
{
return std::hash<std::string>{}(o.unique_name);
}
};
}
bool operator ==(const object& lhs, const object& rhs)
{
return lhs.unique_name == rhs.unique_name;
}
让你可以像这样编写查找代码
using object_table = std::unordered_set<object>;
class objects
{
object_table _table;
public:
object const&operator[](std::string const&name) const
{
if (auto it = object_table.find(object{name}); it != object_table.end())
return *it
else
throw();
}
};
这确实要求 object
可以从单个 std::string
构造,并且它用于初始化 unique_name
。
关于c++ - 唯一命名对象表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51659826/