[英]Using of const for std::pair in c++
For implementing binary search tree I am wandering why we put Const before K in std::pair?为了实现二叉搜索树,我想知道为什么我们在 std::pair 中将 Const 放在 K 之前?
template<class K,class V>
class BST {
public:
class Node {
public:
pair<const K, V> data; // pair < data_type1, data_type2 > Pair_name;
unique_ptr<Node> left; // Create a unique_ptr object through raw pointer
unique_ptr<Node> right;
unique_ptr<Node> parent;
Node(const K& k, const V& v): //constructor
data{std::move(k),std::move(v)}, right(nullptr),left(nullptr),parent(nullptr)
{
}
~Node() noexcept = default;
Because, logically, the node keys in your data structure must be immutable : immune from change.因为,从逻辑上讲,数据结构中的节点键必须是不可变的:不受更改的影响。 That's to maintain the proper structural layout, which depends on the relative ordering (by key.) of the nodes.
那是为了保持正确的结构布局,这取决于节点的相对顺序(按键)。
If a node needs to be renamed, higher-level algorithms need to be deployed in order to do that.如果需要重命名节点,则需要部署更高级别的算法才能做到这一点。
Sure, there's no code in your snippet that would even try to modify a key — and why would there be?当然,您的代码段中没有任何代码甚至会尝试修改密钥——为什么会有呢? It wouldn't compile!
它不会编译! — but putting the
const
there enforces that at compile-time if anybody forgets and tries to do it. - 但是如果有人忘记并尝试这样做,则将
const
放在那里会在编译时强制执行。 So, it's for the same reason as any other usage of const
: enforcing immutability .因此,它的原因与
const
的任何其他用法相同:强制不变性。
std::map
containers also store std::pair<const K, V>
, for just the same reason.出于同样的原因,
std::map
容器也存储std::pair<const K, V>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.