简体   繁体   中英

Appending an std::list into an vector of std::list

I have a vector which is a collection of the list and that list is collection of ints. Like:

std::vector<std::list<int> > vec;

I am trying to append an std::list at an index of std::vector.

Please consider this code:

#include<iostream>
#include<list>
#include<vector>

namespace NM {
  std::vector<std::list<int> > vec;
  class CC {
    public:
    static void func();
  };
}

void NM::CC::func() {
  std::list<int> l1;
  l1.push_back(1);
  l1.push_back(2);
  l1.push_back(3);
  l1.push_back(4);
  std::copy(l1.begin(), l1.end(), NM::vec.at(0).end());
  // NM::ccInfo[0] = l1;
}

int main() {
  NM::vec.resize(2);
  NM::CC::func();
  int index = 0;
  for (; index != 1; index++) {
    std::list<int> l2 = NM::vec.at(index);
    std::list<int>::iterator it = l2.begin();
    for (; it != l2.end(); ++it) {
      std::cout << "Int = " << *it << std::endl;
    }
  }
}

I am expecting that it should append the list(l1) to NM::vec.at(0) inside func function, if anything already exists at MM::vec.at(0) exists. Another expection is that I should be able to get this information it inside main function. I do not see any output in main function.

Where did my expectation go wrong?

Your code has undefined behaviour since it tries to directly write to NM::vec.at(0).end() and beyond.

To append to the list, replace that line with the following:

std::copy(l1.begin(), l1.end(), std::back_inserter(NM::vec.at(0)));

Here

std::copy(l1.begin(), l1.end(), NM::vec.at(0).end());

you are copying to an empty list. std::copy does not, by default, add elements to the list, instead it copies over existing list elements. This is a common misunderstanding.

To make this work you need to use a handy function called std::back_inserter

#include <iterator>

std::copy(l1.begin(), l1.end(), std::back_inserter(NM::vec.at(0)));

std::back_inserter translates writes to the list into calls to push_back so the list grows as you write elements to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM