How do I correctly copy given range of vector to another vector using std::copy?std::copy/memcpy/memmove optimizationsInitializing std::vector of structspointing to an object in a std::vector of boolPopulate std::deque<std::vector<std::string>> with boost::assign::list_ofFilter std::vector of std::string'sfind in std::vector<std::pair>Initialise a std::vector<std::vector<int> > with boost::assign::list_ofAdding Foo& to a std::vectorCopy members to std::vectorMoving (not copying) part of a vector to another vector using C++98

(Why) May a Beit Din refuse to bury a body in order to coerce a man into giving a divorce?

On the feasibility of space battleships

What professions would a medieval village with a population of 100 need?

Can I switch to third-person while not in 'town' in Destiny 2?

Where is the "conservation" in the first law of thermodynamics?

LeetCode: Pascal's Triangle C#

How big would a Daddy Longlegs Spider need to be to kill an average Human?

The economy of trapping

Why did MS-DOS applications built using Turbo Pascal fail to start with a division by zero error on faster systems?

Potential new partner angry about first collaboration - how to answer email to close up this encounter in a graceful manner

Were there 486SX revisions without an FPU on the die?

How much code would a codegolf golf if a codegolf could golf code?

Check in to 2 hotels at same location

Is a butterfly one or two animals?

The teacher logged me in as administrator for doing a short task, is the whole system now compromised?

In an emergency, how do I find and share my position?

Why can't an Airbus A330 dump fuel in an emergency?

What does it mean to have a subnet mask /32?

Fried gnocchi with spinach, bacon, cream sauce in a single pan

Why does my house heat up, even when it's cool outside?

Can pay be witheld for hours cleaning up after closing time?

If all stars rotate, why was there a theory developed, that requires non-rotating stars?

IndexOptimize - Configuration

Shouldn't the "credit score" prevent Americans from going deeper and deeper into personal debt?



How do I correctly copy given range of vector to another vector using std::copy?


std::copy/memcpy/memmove optimizationsInitializing std::vector of structspointing to an object in a std::vector of boolPopulate std::deque<std::vector<std::string>> with boost::assign::list_ofFilter std::vector of std::string'sfind in std::vector<std::pair>Initialise a std::vector<std::vector<int> > with boost::assign::list_ofAdding Foo& to a std::vectorCopy members to std::vectorMoving (not copying) part of a vector to another vector using C++98






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I found a few pages on moving vector range to another vector, however I am struggling to make it work.



I would like to move elements from sourceVect to destVect, with the elements between sourceVect[1] to sourceVect[1+numToCopy] being moved to the beginning of sourceVect. I tried to do this in the following way:



vector<int> destVect;
vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
int numToCopy = 7;

vector<int>::iterator itSource = sourceVect.begin();
vector<int>::iterator itSourceEnd = sourceVect.begin();
advance(itSource, 1);
advance(itSourceEnd, 1+numToCopy);

std::copy(itSource, itSourceEnd, destVect.begin()); //copy(first,last,output vector ite)


for (vector<int>::iterator it = destVect.begin(); it != destVect.end(); ++it)
cout << ' ' << *it;


But I am getting Debug Assertion Failed, vector iterator + offset out of range in Visual studio. Please note that I am only trying it out in Visual Studio 2015, it has to be implemented in C++98 for mbed at the end, meaning I can't use std::next for example.










share|improve this question
























  • Note that you can use C++11 with Mbed OS through a custom build profile where you can set -std=c++11.

    – Jan Jongboom
    Mar 28 at 9:05

















1















I found a few pages on moving vector range to another vector, however I am struggling to make it work.



I would like to move elements from sourceVect to destVect, with the elements between sourceVect[1] to sourceVect[1+numToCopy] being moved to the beginning of sourceVect. I tried to do this in the following way:



vector<int> destVect;
vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
int numToCopy = 7;

vector<int>::iterator itSource = sourceVect.begin();
vector<int>::iterator itSourceEnd = sourceVect.begin();
advance(itSource, 1);
advance(itSourceEnd, 1+numToCopy);

std::copy(itSource, itSourceEnd, destVect.begin()); //copy(first,last,output vector ite)


for (vector<int>::iterator it = destVect.begin(); it != destVect.end(); ++it)
cout << ' ' << *it;


But I am getting Debug Assertion Failed, vector iterator + offset out of range in Visual studio. Please note that I am only trying it out in Visual Studio 2015, it has to be implemented in C++98 for mbed at the end, meaning I can't use std::next for example.










share|improve this question
























  • Note that you can use C++11 with Mbed OS through a custom build profile where you can set -std=c++11.

    – Jan Jongboom
    Mar 28 at 9:05













1












1








1








I found a few pages on moving vector range to another vector, however I am struggling to make it work.



I would like to move elements from sourceVect to destVect, with the elements between sourceVect[1] to sourceVect[1+numToCopy] being moved to the beginning of sourceVect. I tried to do this in the following way:



vector<int> destVect;
vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
int numToCopy = 7;

vector<int>::iterator itSource = sourceVect.begin();
vector<int>::iterator itSourceEnd = sourceVect.begin();
advance(itSource, 1);
advance(itSourceEnd, 1+numToCopy);

std::copy(itSource, itSourceEnd, destVect.begin()); //copy(first,last,output vector ite)


for (vector<int>::iterator it = destVect.begin(); it != destVect.end(); ++it)
cout << ' ' << *it;


But I am getting Debug Assertion Failed, vector iterator + offset out of range in Visual studio. Please note that I am only trying it out in Visual Studio 2015, it has to be implemented in C++98 for mbed at the end, meaning I can't use std::next for example.










share|improve this question














I found a few pages on moving vector range to another vector, however I am struggling to make it work.



I would like to move elements from sourceVect to destVect, with the elements between sourceVect[1] to sourceVect[1+numToCopy] being moved to the beginning of sourceVect. I tried to do this in the following way:



vector<int> destVect;
vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
int numToCopy = 7;

vector<int>::iterator itSource = sourceVect.begin();
vector<int>::iterator itSourceEnd = sourceVect.begin();
advance(itSource, 1);
advance(itSourceEnd, 1+numToCopy);

std::copy(itSource, itSourceEnd, destVect.begin()); //copy(first,last,output vector ite)


for (vector<int>::iterator it = destVect.begin(); it != destVect.end(); ++it)
cout << ' ' << *it;


But I am getting Debug Assertion Failed, vector iterator + offset out of range in Visual studio. Please note that I am only trying it out in Visual Studio 2015, it has to be implemented in C++98 for mbed at the end, meaning I can't use std::next for example.







c++98 mbed






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 15:47









Tryb GhostTryb Ghost

2499 bronze badges




2499 bronze badges















  • Note that you can use C++11 with Mbed OS through a custom build profile where you can set -std=c++11.

    – Jan Jongboom
    Mar 28 at 9:05

















  • Note that you can use C++11 with Mbed OS through a custom build profile where you can set -std=c++11.

    – Jan Jongboom
    Mar 28 at 9:05
















Note that you can use C++11 with Mbed OS through a custom build profile where you can set -std=c++11.

– Jan Jongboom
Mar 28 at 9:05





Note that you can use C++11 with Mbed OS through a custom build profile where you can set -std=c++11.

– Jan Jongboom
Mar 28 at 9:05












2 Answers
2






active

oldest

votes


















1













std::copy() will not create new elements in the destination container. That means you need to create destVect with the correct size:



vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
vector<int> destVect(sourceVect.size() - 1);


If you can't create it with the correct size, just resize it later on, at the point where you know the size:



destVect.resize(sourceVect.size() - 1);


You can now copy:



copy(sourceVect.begin() + 1, sourceVect.end(), destVect.begin());


However, you can just create destVect with the correct contents to begin with. You don't need to manually copy anything:



vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
vector<int> destVect(sourceVect.begin() + 1, sourceVect.end());


This is the fastest way to do this and (perhaps more importantly) it's not prone to errors. If you do an std::copy but your destination container's size is not large enough, you end up writing into non-allocated memory (buffer overflow.)






share|improve this answer



























  • Unfortunately I can't initialise it with the correct size. At least now I know what the problem is, ill try to get around it by setting the memory beforehand I guess.

    – Tryb Ghost
    Mar 27 at 16:04











  • @TrybGhost In that case, just use resize(). Updated the answer.

    – Nikos C.
    Mar 27 at 16:06


















1













vector::iterator has always supported +, you don't need next or advance. The simplest way is to initialise from a pair of iterators.



 std::vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
std::vector<int>::iterator first = sourceVect.begin() + 1;
std::vector<int>::iterator last = first + numToCopy;
std::vector<int> destVect(first, last); // contains 2,3,4,5,6,7,8


If you can't avoid delaying declaring destVect to the point where you have an appropriate initialiser, you can use assign



 destVect.assign(first, last); // contains 2,3,4,5,6,7,8 overwriting whatever was there before





share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55381327%2fhow-do-i-correctly-copy-given-range-of-vector-to-another-vector-using-stdcopy%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1













    std::copy() will not create new elements in the destination container. That means you need to create destVect with the correct size:



    vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
    vector<int> destVect(sourceVect.size() - 1);


    If you can't create it with the correct size, just resize it later on, at the point where you know the size:



    destVect.resize(sourceVect.size() - 1);


    You can now copy:



    copy(sourceVect.begin() + 1, sourceVect.end(), destVect.begin());


    However, you can just create destVect with the correct contents to begin with. You don't need to manually copy anything:



    vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
    vector<int> destVect(sourceVect.begin() + 1, sourceVect.end());


    This is the fastest way to do this and (perhaps more importantly) it's not prone to errors. If you do an std::copy but your destination container's size is not large enough, you end up writing into non-allocated memory (buffer overflow.)






    share|improve this answer



























    • Unfortunately I can't initialise it with the correct size. At least now I know what the problem is, ill try to get around it by setting the memory beforehand I guess.

      – Tryb Ghost
      Mar 27 at 16:04











    • @TrybGhost In that case, just use resize(). Updated the answer.

      – Nikos C.
      Mar 27 at 16:06















    1













    std::copy() will not create new elements in the destination container. That means you need to create destVect with the correct size:



    vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
    vector<int> destVect(sourceVect.size() - 1);


    If you can't create it with the correct size, just resize it later on, at the point where you know the size:



    destVect.resize(sourceVect.size() - 1);


    You can now copy:



    copy(sourceVect.begin() + 1, sourceVect.end(), destVect.begin());


    However, you can just create destVect with the correct contents to begin with. You don't need to manually copy anything:



    vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
    vector<int> destVect(sourceVect.begin() + 1, sourceVect.end());


    This is the fastest way to do this and (perhaps more importantly) it's not prone to errors. If you do an std::copy but your destination container's size is not large enough, you end up writing into non-allocated memory (buffer overflow.)






    share|improve this answer



























    • Unfortunately I can't initialise it with the correct size. At least now I know what the problem is, ill try to get around it by setting the memory beforehand I guess.

      – Tryb Ghost
      Mar 27 at 16:04











    • @TrybGhost In that case, just use resize(). Updated the answer.

      – Nikos C.
      Mar 27 at 16:06













    1












    1








    1







    std::copy() will not create new elements in the destination container. That means you need to create destVect with the correct size:



    vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
    vector<int> destVect(sourceVect.size() - 1);


    If you can't create it with the correct size, just resize it later on, at the point where you know the size:



    destVect.resize(sourceVect.size() - 1);


    You can now copy:



    copy(sourceVect.begin() + 1, sourceVect.end(), destVect.begin());


    However, you can just create destVect with the correct contents to begin with. You don't need to manually copy anything:



    vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
    vector<int> destVect(sourceVect.begin() + 1, sourceVect.end());


    This is the fastest way to do this and (perhaps more importantly) it's not prone to errors. If you do an std::copy but your destination container's size is not large enough, you end up writing into non-allocated memory (buffer overflow.)






    share|improve this answer















    std::copy() will not create new elements in the destination container. That means you need to create destVect with the correct size:



    vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
    vector<int> destVect(sourceVect.size() - 1);


    If you can't create it with the correct size, just resize it later on, at the point where you know the size:



    destVect.resize(sourceVect.size() - 1);


    You can now copy:



    copy(sourceVect.begin() + 1, sourceVect.end(), destVect.begin());


    However, you can just create destVect with the correct contents to begin with. You don't need to manually copy anything:



    vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
    vector<int> destVect(sourceVect.begin() + 1, sourceVect.end());


    This is the fastest way to do this and (perhaps more importantly) it's not prone to errors. If you do an std::copy but your destination container's size is not large enough, you end up writing into non-allocated memory (buffer overflow.)







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 27 at 16:04

























    answered Mar 27 at 16:00









    Nikos C.Nikos C.

    41.5k7 gold badges50 silver badges79 bronze badges




    41.5k7 gold badges50 silver badges79 bronze badges















    • Unfortunately I can't initialise it with the correct size. At least now I know what the problem is, ill try to get around it by setting the memory beforehand I guess.

      – Tryb Ghost
      Mar 27 at 16:04











    • @TrybGhost In that case, just use resize(). Updated the answer.

      – Nikos C.
      Mar 27 at 16:06

















    • Unfortunately I can't initialise it with the correct size. At least now I know what the problem is, ill try to get around it by setting the memory beforehand I guess.

      – Tryb Ghost
      Mar 27 at 16:04











    • @TrybGhost In that case, just use resize(). Updated the answer.

      – Nikos C.
      Mar 27 at 16:06
















    Unfortunately I can't initialise it with the correct size. At least now I know what the problem is, ill try to get around it by setting the memory beforehand I guess.

    – Tryb Ghost
    Mar 27 at 16:04





    Unfortunately I can't initialise it with the correct size. At least now I know what the problem is, ill try to get around it by setting the memory beforehand I guess.

    – Tryb Ghost
    Mar 27 at 16:04













    @TrybGhost In that case, just use resize(). Updated the answer.

    – Nikos C.
    Mar 27 at 16:06





    @TrybGhost In that case, just use resize(). Updated the answer.

    – Nikos C.
    Mar 27 at 16:06













    1













    vector::iterator has always supported +, you don't need next or advance. The simplest way is to initialise from a pair of iterators.



     std::vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
    std::vector<int>::iterator first = sourceVect.begin() + 1;
    std::vector<int>::iterator last = first + numToCopy;
    std::vector<int> destVect(first, last); // contains 2,3,4,5,6,7,8


    If you can't avoid delaying declaring destVect to the point where you have an appropriate initialiser, you can use assign



     destVect.assign(first, last); // contains 2,3,4,5,6,7,8 overwriting whatever was there before





    share|improve this answer





























      1













      vector::iterator has always supported +, you don't need next or advance. The simplest way is to initialise from a pair of iterators.



       std::vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
      std::vector<int>::iterator first = sourceVect.begin() + 1;
      std::vector<int>::iterator last = first + numToCopy;
      std::vector<int> destVect(first, last); // contains 2,3,4,5,6,7,8


      If you can't avoid delaying declaring destVect to the point where you have an appropriate initialiser, you can use assign



       destVect.assign(first, last); // contains 2,3,4,5,6,7,8 overwriting whatever was there before





      share|improve this answer



























        1












        1








        1







        vector::iterator has always supported +, you don't need next or advance. The simplest way is to initialise from a pair of iterators.



         std::vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
        std::vector<int>::iterator first = sourceVect.begin() + 1;
        std::vector<int>::iterator last = first + numToCopy;
        std::vector<int> destVect(first, last); // contains 2,3,4,5,6,7,8


        If you can't avoid delaying declaring destVect to the point where you have an appropriate initialiser, you can use assign



         destVect.assign(first, last); // contains 2,3,4,5,6,7,8 overwriting whatever was there before





        share|improve this answer













        vector::iterator has always supported +, you don't need next or advance. The simplest way is to initialise from a pair of iterators.



         std::vector<int> sourceVect = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20;
        std::vector<int>::iterator first = sourceVect.begin() + 1;
        std::vector<int>::iterator last = first + numToCopy;
        std::vector<int> destVect(first, last); // contains 2,3,4,5,6,7,8


        If you can't avoid delaying declaring destVect to the point where you have an appropriate initialiser, you can use assign



         destVect.assign(first, last); // contains 2,3,4,5,6,7,8 overwriting whatever was there before






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 27 at 16:08









        CalethCaleth

        21.6k2 gold badges24 silver badges44 bronze badges




        21.6k2 gold badges24 silver badges44 bronze badges






























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55381327%2fhow-do-i-correctly-copy-given-range-of-vector-to-another-vector-using-stdcopy%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해