修改列表列表

modifying the list of lists

有这样的结构:

  std::list<std::list<std::string>> data;

我需要遍历顶级列表并根据某些条件附加内部列表。像这样:

  std::for_each(data.begin(), data.end(), 
                 [<some variable required for the logic>]
                 (const std::list<std::string>& int_list) {
         if(...) 
              int_list.push_back(...);
  });

你看这个代码是无效的,因为for_each不能修改序列。 你会推荐我做什么来执行我需要的(不修改初始数据结构)?

您可以像这样使用 C++11 ranged based for loops

std::list<std::list<std::string>> data;
for (auto & e : data)
{
    if (some_condition)
        e.push_back(some_data)
}