Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an element to a Vector while iterating over it

As the title says, I want to add an element to a std::vector in certain cases while iterating through the vector. With the following code, I'm getting an error "Debug assertion failed". Is it possible to achieve what I want to do?

This is the code I have tested:

#include <vector>

class MyClass
{
public:
    MyClass(char t_name)
    {
        name = t_name;
    }
    ~MyClass()
    {
    }
    char name;
};

int main()
{
    std::vector<MyClass> myVector;
    myVector.push_back(MyClass('1'));
    myVector.push_back(MyClass('2'));
    myVector.push_back(MyClass('3'));

    for each (MyClass t_class in myVector)
    {
        if (t_class.name == '2')
             myVector.push_back(MyClass('4'));
    }
    return 0;
}

EDIT:

Well, I thought for each was standard C++, but it seems that it's a Visual Studio feature:

for each, in

Visual c++ "for each" portability

like image 229
Alex Avatar asked Jun 18 '16 18:06

Alex


1 Answers

The act of adding or removing an item from a std::vector invalidates existing iterators. So you cannot use any kind of loop that relies on iterators, such as for each, in, range-based for, std::for_each(), etc. You will have to loop using indexes instead, eg:

int main()
{
    std::vector<MyClass> myVector;

    myVector.push_back('1');
    myVector.push_back('2');
    myVector.push_back('3');

    std::vector<MyClass>::size_type size = myVector.size();
    for (std::vector<MyClass>::size_type i = 0; i < size; ++i)
    {
        if (myVector[i].name == '2')
        {
             myVector.push_back('4');
             ++size; // <-- remove this if you want to stop when you reach the new items
        }
    }

    return 0;
}
like image 189
Remy Lebeau Avatar answered Sep 18 '22 22:09

Remy Lebeau