简体   繁体   English

为什么选择STL <set> 重载运算符&lt;函数必须是const函数吗?

[英]Why STL <set> the overload operator < function must be a const function?

class Test
{

public:

    int v;
    Test(int s)
    {
        v = s;
    }

    bool operator < (const Test & b) const
    {
        return v < b.v;
    }
};

int main()
{
    set <Test> t2;
    return 0;
}

Why must I use a const function when I overload the less operator? 重载less运算符时,为什么必须使用const函数? If i don't write the "const" there, it won't pass the compiling. 如果我不在那里写“ const”,它将不会通过编译。 So i don't know why MUST I write the "const" there? 所以我不知道为什么我必须在那里写“ const”?

The reason is that std::set is a bit special: the values it stores must not change (likewise the key_type in a std::map ). 原因是std::set有点特殊:它存储的值不得更改(同样, std::mapkey_type )。 This is because set is a sorted container, and it needs to know how to sort the values; 这是因为set是一个排序的容器,它需要知道如何对值进行排序。 changing the values within the set could result in a broken program, because set::set has no way to know that the values have been changed and therefore would need to be sorted again. 更改集合中的值可能会导致程序损坏,因为set::set无法知道值已更改,因此需要重新排序。

If the comparison function were allowed to modify the values, then it could never be used, because the values in a set are always const. 如果允许比较函数修改值,则永远不能使用它,因为集合中的值始终是const。

As an aside, it is true that some modifications of the values are permissible, specifically modifications which do not affect the sort order. 顺便说一句,确实可以对值进行一些修改,特别是那些不影响排序顺序的修改。 So if you have a set with a custom sort function which sorts by one field of a struct, you can modify other fields of the struct because the sort order will remain the same. 因此,如果您有一个带有自定义排序功能的集合,该集合按结构的一个字段排序,则可以修改结构的其他字段,因为排序顺序将保持不变。 But std::set has no way to understand which fields are important to the sort order and which are not, so the whole value is const. 但是std::set无法了解哪些字段对排序顺序很重要,哪些字段对排序顺序不重要,因此整个值都是const。 You can do tricks like making some fields mutable to deal with this, but in most cases it is not necessary (eg you can use a map instead, and put the modifiable parts in the value_type instead). 您可以做一些技巧,例如使某些字段mutable以解决此问题,但是在大多数情况下,这是没有必要的(例如,您可以改用地图,而将可修改的部分放在value_type )。

You are not required to do so. 您不需要这样做。 It's generally recommend because one shouldn't modify objects in the process of comparing them. 通常建议这样做,因为在比较对象的过程中不应修改对象。 set<Test> makes it a requirement by passing const references to operator< . set<Test>通过将const引用传递给operator<来使其成为必需项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM