在C++中,我有一個按名稱排序的類,它是std::string
。我希望在std::map
或std::set
中每個唯一名稱只有一個。如果我的鑰匙是我的價值的一部分,我應該使用地圖還是集合?
我可以使用std::set
,因爲operator<
將通過名稱排序我的實例,但是,我需要通過名稱來查找實例。然而,使用鍵是名字的映射是直接的,但是,我也可以使用一個集合並構造一個我的類的虛擬實例,其名稱是我希望查找的集合中定位給定類的實際實例名稱。
我想我應該隨地圖一起使代碼簡單直接,但不知道是否可能有一種方法去設置,因爲密鑰實際上是我的對象的一部分,從而避免了一些冗餘。
有沒有辦法使用該設置,並能夠通過他們的鍵以清晰的方式定位對象,或者我應該只使用一張地圖並完成它?
下面是要被插入(草稿形式)的類,並在每一個目錄中有任一鍵固定切斷節點名稱的集合或節點(S)的圖:
class Node {
public:
Node(Directory &parent, const std::string &name)
: _name(name),
_parent(&parent),
_isRoot(false) {
if (name.empty()) {
throw InvalidNodeNameError(name);
}
}
protected:
// This is only used for the root directory:
Node()
: _name(""),
_parent(0),
_isRoot(true) {
}
Node(const std::string &name)
: _name(name),
_parent(0),
isRoot(false) {
}
public:
virtual ~Node() {
if (parent()) {
parent()->remove(*this);
}
}
bool operator<(const Node &rhs) const {
return _name < rhs._name;
}
Directory *parent() const {
return _parent;
}
void setParent(Directory *parent) {
_parent = parent;
}
const std::string &name() const {
return _name;
}
bool isRoot() const {
return _isRoot;
}
std::string pathname() const {
std::ostringstream path;
if (parent()) {
path << parent()->pathname() << '/';
} else {
path << '/';
}
path << name();
return path.str();
}
private:
// Not defined:
Node(const Node &rhs);
Node &operator=(const Node &rhs);
private:
std::string _name;
Directory *_parent;
const bool _isRoot;
};
[我問了一個非常類似的問題之前(http://stackoverflow.com/questions/7075603/using-an-unordered-map-where-key-is-a -member-的-T)。實際上所有的答案都很不錯。唯一的區別是你的參與比較,而我的哈希包括'map'和'unordered_map'。 –
這可能有助於看到你的班級。 – ThomasMcLeod
現在添加了草稿代碼。 – WilliamKF