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

标签 c++ dynamic nested

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

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/

相关文章:

c++ - 用 c 包装一个 c++ 库? (不要 "extern c")

c# - 在 C# 中解决方法重载的优先规则是什么?

dynamic - C# 4.0 'dynamic' 和 foreach 语句

仅当表达式的值不是 None 时才返回表达式的 Python 语法

c++ - 设置背景颜色 CMDIFrameWnd

c++ - std::deque<char> 上的简单插入-删除-插入给出了奇怪的结果

c++ - 在 C++ 中使用 switch 评估字符串

c# - 具有动态参数的表达式树

具有嵌套对象的elasticsearch复合aggs

json - 我如何在 spark(scala 或 java)中将平面数据帧转换为嵌套的 json