CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2017
    Posts
    9

    Question Vector Size change inside loop

    Hi,
    Can we change the vector size during loop like

    Code:
    vector<int> vec;
    vec.push_back(10);
    vec.push_back(100);
    vec.push_back(1000);
    vec.push_back(10000);
    
    for(auto item : vec)
    {
            cout<<item<<endl;
            if(item == 10000)
            vec.push_back(5);
    }
    output
    10
    100
    1000
    10000

    should not it
    10
    100
    1000
    10000
    5

    if not why?

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: Vector Size change inside loop

    The range based for loop is equivalent to

    Code:
    	for (auto item = vec.begin(), ie = vec.end(); item != ie; ++item)
    	{
    		cout << *item << endl;
    		if (*item == 10000)
    			vec.push_back(5);
    	}
    so additions to the end of the vector won't be included as part of the for as the end of the vector is determined at the start of the loop.

    Note that 5 has indeed been added to the end of the vector. If

    Code:
    	for (const auto& i : vec)
    		cout << i << endl;
    is added after the code in post #1 then the display is

    Code:
    10
    100
    1000
    10000
    10
    100
    1000
    10000
    5
    showing that 5 has indeed been added.

    Note that if a relocation happens because there is insufficient capacity within the existing vector, then all iterators are invalidated as part of the relocation. So performing operations within a loop like this that may invalidate iterators is not recommended and is not guaranteed to work correctly if a relocation occurs.
    Last edited by 2kaud; August 23rd, 2017 at 04:23 PM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured