Search code examples
stlstdvectorstdlist

Initialize std::vector from std::list using iterators


I'm trying to initialize a std::vector from a std::list efficiently, but I'm not having any luck.

For example, it'd like to something like this:

void myFunc(std::list<double>::iterator begin, std::list<double>::iterator end)
{
    std::vector <double> data(begin, end);
    // or
    std::vector <double> data;
    data::insert(data.begin(), data.end());
}

However, this is not working since the containers seem to only support their own iterator types? Am I missing something? Is what I am trying to accomplish not that easily possible?


Solution

  • Your first version

    std::vector<double> data(begin, end);
    

    is correct.

    You second version should be

    std::vector<double> data;
    data.insert(data.begin(), begin, end);