gpt4 book ai didi

c++ - 通过 C++ 中的迭代器改变集合中的集合

转载 作者:太空狗 更新时间:2023-10-29 22:54:36 26 4
gpt4 key购买 nike

我想通过大致这样的方式来改变“out”:

set<list<int>> out = {{1, 2, 3}, {6, 7, 8}};

for (auto &it : out)
{
it.push_front(2);
}

上面的代码会编译错误:

passing ‘const std::__cxx11::list’ as ‘this’ argument discards qualifiers [-fpermissive] it.push_front(2);

我隐约知道这种情况可能会丢弃一些 const 限定符。有没有办法解决它,或者我应该采用一些不同的方法?

最佳答案

将某些东西插入集合时,它会被放入红黑树中以表示排序顺序并帮助插入唯一值。在插入后更改值会破坏集的核心功能。

C++文档中的集合迭代器有注释

https://en.cppreference.com/w/cpp/container/set/begin

Because both iterator and const_iterator are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions.

这也意味着您可以通过其他方式更改它们,但这不是一个好主意。

列表容器没有这样的限制,在我看来是正确的选择。

https://en.cppreference.com/w/cpp/container/list/begin

#include <list>
#include <iostream>

int main()
{
std::list<std::list<int>> listOfLists = {{1, 2, 3}, {6, 7, 8}};

for (auto& containedList : listOfLists)
{
containedList.push_front(2);
}

for (auto& containedList : listOfLists)
{
std::cout << "[";
for (auto& listItem : containedList) {
std::cout << listItem;
}
std::cout << "]" << std::endl;
}

return 0;
}

关于c++ - 通过 C++ 中的迭代器改变集合中的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54836818/

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