Conditionally erase object from a vector of objects.

Help. I get a runtime crash with this code. It compiles fine in Visual Studio Community.

I want to conditionally erase an object from a vector of objects. When the condition is met, erase the object in that loop's iteration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Foo
{
public:
	Foo(int i);
	int mI;
};

Foo::Foo(int i)
    : mI(i)
{
}

int main()
{
	std::vector<Foo> foos{ {23},{35},{82}};
	int i = 0;
	for (auto it = foos.begin(); it != foos.end();)
	{
		if (foos[i].mI == 23)
			foos.erase(it);
		else {
			++it;
			++i;
		}
	}
    return 0;
}.
Last edited on
Read up on the erase method. It returns a new iterator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>

class Foo
{
    int mI;
public:
    Foo(int i) : mI{i} {}
    bool operator==(int n) const { return mI == n; }
    friend std::ostream& operator<<(std::ostream& os, const Foo& f)
    {
        return os << f.mI;
    }
};

int main()
{
    std::vector<Foo> foos{ 23, 35, 82 };
    for (auto it = foos.begin(); it != foos.end();)
        if (*it == 23)
            it = foos.erase(it);
        else
            ++it;
    for (const auto& f: foos)
        std::cout << f << '\n';
}
Topic archived. No new replies allowed.