gpt4 book ai didi

C++:set::insert with iterators and sets of sets

转载 作者:行者123 更新时间:2023-11-28 03:11:46 27 4
gpt4 key购买 nike

我有一组称为 nets 的整数集,我正在尝试对其进行迭代以确定是否已将来自或来自的整数添加到现有集合中;如果是这样,我将它们添加到现有集合中(这是为了跟踪电网中所有短路的组合)。

但是,我无法让 set::insert 函数工作!我可以使用 (*it).count 来确定是否已经将任一 int 添加到集合中,但是 (*it).insert 不起作用(我总是收到错误 No matching member function call to '插入')。但是,如果我只是创建一组整数,setName.insert(to) 可以正常工作。

我的代码有什么问题?

for (std::set<std::set<int>>::iterator it=nets.begin(); it!=nets.end(); ++it) {  
if ((*it).count(to) || (*it).count(from)) {
currentSet = (*it);
(*it).insert(to);
(*it).insert(from);
addedToExistingSet = true;
}
}

最佳答案

由于 std::set 是一个关联容器,它包含一组已排序的 T 类型的唯一对象,您不能修改它里面的对象,因为你会使 set 无效。

如果允许,您将被允许从容器下方更改项目值,可能会改变顺序。

标准说:

23.2.4 Associative containers [associative.reqmts]

iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators.

您应该考虑为外部容器使用另一个容器,例如 std::vector

关于C++:set::insert with iterators and sets of sets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18277038/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com