简体   繁体   English

在 c++ 中对 std::pair 使用 const

[英]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.

相关问题 使用std :: pair的C ++ const正确性 - C++ const correctness with std::pair C ++:在开关中使用std :: pair的可能性 - c++: the possibility of using std::pair in switch 这是std :: get的C ++缺陷吗? <T> (const std :: pair <const T, U> &)由于const T而无法编译? - Is this a defect in C++ that std::get<T> ( const std::pair<const T, U>& ) fail to compile due to const T? 英特尔C ++错误:“pair”不是非静态数据成员或类“std :: pair”的基类 <const int, double> ” - Intel C++ error: “pair” is not a nonstatic data member or base class of class “std::pair<const int, double>” C ++ std :: vector <std::pair<const int, int> &gt;无法插入元素 - C++ std::vector<std::pair<const int, int>> can not insert element 如何理解C ++错误,“不匹配&#39;operator ==&#39;(操作数类型为&#39;std :: pair&#39;和&#39;const int&#39;)”? - How to understand C++ error, “no match for 'operator==' (operand types are 'std::pair' and 'const int')”? 在C ++中对std :: pair和std :: map进行子类化 - Subclassing std::pair and std::map in C++ c ++ std :: pair,std :: vector&memcopy - c++ std::pair, std::vector & memcopy C++:无法使用“=”运算符更改 std::pair 的值 - C++: Unable to change the value of a std::pair using the “=” operator 在std :: pair中进行常量转换 - Const Conversion in std::pair
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM