gpt4 book ai didi

c++ - C++中的动态嵌套?

转载 作者:行者123 更新时间:2023-11-30 00:58:00 26 4
gpt4 key购买 nike

我有一个列表列表。所有元素都将在运行时插入。我想尝试所有列表中的所有组合。所以简单的解决方案浮现在脑海中

for ( l1 in L1)   
{ for ( l2 in L2)
{ for ( l3 in L3)
{
... // use the pair (l1,l2,l3)
}
}
}

但是我不知道编译时需要多少个for。那么我如何遍历 C++ 中的所有对呢?

最佳答案

使用递归。

typedef std::list<std::list<int>> ListOfList;

void actOnHelper(ListOfList::const_iterator c, ListOfList::const_iterator end, std::list<int> v)
{
if (c == e) {
// do something on v
} else {
ListOfList::const_iterator nextc(c);
++nextc;
for (std::list<int>::const_iterator i = c->begin(), e = c->end(); i != e; ++i) {
v.push_back(*i);
actOnHelper(nextc, end, v);
v.pop_back();
}
}
}
void actOn(std::list<std::list<int>> const& l)
{
actOnHelper(l.begin(), l.end(), std::list<int>());
}

关于c++ - C++中的动态嵌套?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7042798/

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