这是我的问题的最小功能:
void solve(void)
{
set<set<int> > test;
for(set<set<int> >::iterator it = test.begin(); it != test.end(); ++it) {
// (*it)'s type is set<int> right? but why I cannot insert a int into this?
it -> insert(1);
}
}
编译器告诉我 no matching function for call to 'std::set<int>::insert(int) const'
。我真的很困惑,为什么不使用
std::set<int>::insert(int)
而不使用 const
?我怎样才能做到这一点?我真的能做到吗?*** first edited ***
我知道我可以删除像 it = test.erase(it)
这样的元素,我也知道我可以使用 test.insert(<a set<int> value>)
,所以可以先插入然后删除原始元素吗?但是看起来很麻烦吧?*** seconed edited ***
关于用例:在我知道不相交集数据结构之前,我想解决它的问题,所以我需要处理 set<int> type data
中的 set<set<int>> type data
。让我感到不安的是,我发现我无法更改循环中的内部 set
,因此我无法合并这些内部集 - (或者我可以,我尝试将内部集值的那些元素放入临时 set
中,然后删除原始的 set
s,然后我将临时 set
插入 set<set>
。但它确实看起来很难看)。所以我知道要做到,但我不知道为什么迭代器是 const
,我也想知道更好的方法来处理 set
中的 set
。*** third edited ***
感谢@anurag-dhadse 指出语法错误。谢谢。
最佳答案
您的 it->insert(1)
尝试更改 set<int>
内外set<set<int>>
, 这样做可能会改变 *it
的位置。应该存储在外部 set
,这将违反 class invariants通过不保持元素排序。为避免这种情况,外部 set
只给 it
const
访问 set<int>
元素
如果要修改 set<int>
元素,您需要 extract
从外部set
,修改,然后insert
它回到它现在应该去的任何地方。
关于c++ - 为什么我无法更改 `set<set<int>>` 循环中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62847368/