简体   繁体   English

我从 std::set 得到 const_iterator 而不是迭代器

[英]I get const_iterator instead of iterator from std::set

I have the following code which does not compile at all.我有以下根本无法编译的代码。 It says that I cannot convert const Node to Node& but Node is not const nor methods of A refer to a const this nor std::set is const.它说我不能将const Node转换为Node&Node不是const也不是A方法指的是const this也不是std::set是 const。

Where am I wrong?我哪里错了?

#include <set>
#include <string>

struct Node
{
    std::string name;
};

struct NodeNameComparator
{
    using is_transparent = void;
    bool operator()(const Node &a, const std::string &b) const { return a.name < b; }
    bool operator()(const std::string &a, const Node &b) const { return a < b.name; }
    bool operator()(const Node &a, const Node &b) const { return a.name < b.name; }
};


struct A
{
    std::set<Node, NodeNameComparator> nodeset;
    Node &add_or_get_node(const std::string &name)
    {
        std::set<Node, NodeNameComparator>::iterator it = nodeset.template find(name);
        // IT WORKS BUT IT IS A WORKAROUND.
        //return it == nodeset.end() ? const_cast<Node&>(*(nodeset.insert(*new Node{name}).first)) : const_cast<Node&>(*it);
        //ERROR!!!
        return it == nodeset.end() ? *(nodeset.insert(*new Node{name}).first) : *it;
    };
};

int main() { return 0; }

std::set is not just a set of elements, it is a sorted set of unique elements. std::set不仅仅是一组元素,它是一组有序的唯一元素。 Elements of std::set are immutable by design, so that you cannot break std::set invariant by modifying its elements. std::set的元素在设计上是不可变的,因此您不能通过修改其元素来破坏std::set不变量。 That's the reason why std::set::iterator and std::set::const_iterator are both constant iterators.这就是为什么std::set::iteratorstd::set::const_iterator都是常量迭代器的原因。

Cppreference on std::set reads : std::set上的 Cppreference读取

Member type       Definition 

iterator          Constant LegacyBidirectionalIterator
const_iterator    Constant LegacyBidirectionalIterator

See also this LWG issue :另请参阅此 LWG 问题

Keys in an associative container are immutable.关联容器中的键是不可变的。 ... For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. ...对于值类型与键类型相同的关联容器, iteratorconst_iterator都是常量迭代器。

Rationale : ... if elements were mutable, there would be no compile-time way to detect of a simple user oversight which caused ordering to be modified.基本原理: ...如果元素是可变的,则没有编译时方法来检测导致修改排序的简单用户疏忽。 There was a report that this had actually happened in practice, and had been painful to diagnose.有报道说这在实践中确实发生过,而且诊断起来很痛苦。 If users need to modify elements, it is possible to use mutable members or const_cast .如果用户需要修改元素,可以使用可变成员或const_cast

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

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