Search code examples
c++stlstl-algorithm

modifying the list of lists


there is a structure like this:

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

I need to go throu the top level list and append internal lists against some criteria. something like this:

  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(...);
  });

you see this code is not valid, because for_each can't modify the sequence. what would you recommend me to perform what I need (without modifying initial data structure)?


Solution

  • You can use a C++11 ranged based for loops like:

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